## IMPLEMENTATION OF CALCULATOR USING LEX AND YACC

				
Lex
%{
#include"y.tab.h"
#include
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval=atof(yytext);return
NUMBER;}
log |
LOG {return LOG;}
In {return nLOG;}
sin |
SIN {return SINE;}
cos |
COS {return COS;}
tan |
TAN {return TAN;}
mem {return MEM;}
[\t];
\$return 0; \n|. return yytext[0]; %%     Yacc %{ double memvar; %} %union { double dval; } %tokenNUMBER %tokenMEM %token LOG SINE nLOG COS TAN %left '-' '+' %left '*' '/' %right '^' %left LOG SINE nLOG COS TAN %nonassoc UMINUS %typeexpression %% start:statement'\n' |start statement'\n' ; statement:MEM'='expression {memvar=$3;}
| expression{printf("Answer=%g\n",$1);} ; expression:expression'+'expression {$$=1+3;} | expression '-' expression {$$=$1-$3;} | expression '*' expression {$$=1*3;} | expression '/' expression { if(3==0) yyerror("divide by zero"); else$$=$1/$3; } |expression'^'expression {$$=pow(1,3);} ; expression:'-'expression %prec UMINUS{$$=-$2;}
|'('expression')'{$$=2;} |LOG expression {$$=log($2)/log(10);} |nLOG expression {$$=log(2);} |SINE expression {$$=sin($2*3.14/180);}
|COS expression {$$=cos(2*3.14/180);} |TAN expression {$$=tan($2*3.14/180);} |NUMBER {$$=1;} |MEM {$$=memvar;} ; %% main() { printf("Enter the expression"); yyparse();} int yyerror(char *error) { printf("%s\n",error); }   OUTPUT: [linuxpert@fosslab ~]$ vi cal.l
[linuxpert@fosslab ~]$lex cal.l [linuxpert@fosslab ~]$ yacc -d cal.y
[linuxpert@fosslab ~]$cc lex.yy.c y.tab.c -ll -lm [linuxpert@fosslab ~]$ ./a.out
Enter the expression(5+2)*(3-1)/(2)
Answer=7