Program To Calculate Mathematical Expressions > Lex and Yacc Program
Program To Calculate Mathematical Expressions > Lex and Yacc Program
System Programming and Compiler Construction
Programs:
pratspcc3.l:
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[\t]+ ;
[0-9]+ {yylval = atoi(yytext); return(num);}
\n {return 0;}
. {return (yytext[0]);}
%%
int yywrap()
{
return 1;
}
spcc3.y:
%{
#include<stdio.h>
#include<stdio.h>
%}
%Start S
%token num
%left '+''-'
%left '*''/'
%%
S:E {printf("RESULT = %d\n",$1);
}
;
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|num {$$=$1;}
%%
main(){
printf("ENTER THE EXPRESSION");
yyparse();
}
int yyerror()
{
return (1);
}
OUTPUT:
[root@localhost ~]# cd Desktop
[root@localhost Desktop]# yacc -d spcc3.y
[root@localhost Desktop]# lex pratspcc3.l
[root@localhost Desktop]# cc -o out3 lex.yy.c y.tab.c -ll
[root@localhost Desktop]# ./out3
ENTER THE EXPRESSION5+4-1
RESULT = 8
[root@localhost Desktop]# ./out3
ENTER THE EXPRESSION6/2+7
RESULT = 10
Comments
Post a Comment