Ex. No: 4 A
Date:
4A. PROGRAM TO RECOGNIZE A VALID ARITHMETIC
EXPRESSION THAT USESOPERATOR +, - , * AND / USING YACC
AIM:
To write a Yacc program to valid arithmetic expression using Yacc
ALGORITHM:
Step-1:Reading an expression
Step-2: Checking the validating of the given expression according to the rule using yacc.
Step-3:Using expression rule print the result of the given values
PROGRAM
vae.l
%{
#include"y.tab.h"
#include<math.h>
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return NUM;}
[+] {return '+';}
[-] {return '-';}
[*] {return '*';}
[/] {return '/';}
[\t]+;
[\n] {return 0;}
%%
vae.y
%{
#include<stdio.h>
%}
%token NUM
%left '-''+'
%right '*''/'
%%
start: exp {printf("%d\n",$$);}
exp:exp'+'exp {$$=$1+$3;}
|exp'-'exp {$$=$1-$3;}
|exp'*'exp {$$=$1*$3;}
|exp'/'exp
{
if($3==0)
yyerror("error");
else
{
$$=$1/$3;
}
}
|'('exp')' {$$=$2;}
|NUM {$$=$1;}
;
%%
main()
{
printf("Enter the Expr. in terms of integers\n");
if(yyparse()==0)
printf("Success\n");
}
yywrap(){}
yyerror()
{
printf("Error\n");
}
OUTPUT:
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\YACC\CD4A>lex vae.l
D: \MOHANRAJ\\CS6612 COMPILER LAB\lex_yacc\YACC\CD4A>yacc -d vae.y
D: \MOHANRAJ\\CS6612 COMPILER LAB\lex_yacc\YACC\CD4A>cc lex.yy.c y.tab.c
D: \MOHANRAJ\\CS6612 COMPILER LAB\lex_yacc\YACC\CD4A>a.exe
Enter the Expr. in terms of integers
1+2*3-4/2
5
Success
D: \MOHANRAJ\\CS6612 COMPILER LAB\lex_yacc\YACC\CD4A>a.exe
Enter the Expr. in terms of integers
m+3-4
mError
RESULT:
Thus the program for validating arithmetic expression was done.
No comments:
Post a Comment