YACC to evaluate an expression (simple calculator program for addition and subtraction, multiplication, division)

/*Program in YACC to evaluate an expression (simple calculator program for addition and
subtraction, multiplication, division).*/

File Name : calc10.y
%{
 #include<stdio.h>
int yylex(void);
int yyerror(char *);
%}

%token NAME NUMBER

%%
statement : NAME '=' expression
 | expression { printf("=%d\n",$1);}
 ;
expression:expression'+' NUMBER{$$ = $1+$3;}
 |expression '-' NUMBER {$$ = $1-$3;}
 |expression '*' NUMBER {$$ = $1*$3;}
 |expression '/' NUMBER { if ($3!=0){ $$ = $1/$3; }else { printf("Error: divide by Zero"); } }
 |NUMBER {$$=$1;}
 ;

%%
int main()
{
yyparse();
return 0;
}
int yyerror(char *s)
{
 printf("%s",s);
}

File Name : calc10.l
%{
 #include "y.tab.h"
 extern int yylval;
%}

%%
[0-9]+ { yylval=atoi(yytext);return NUMBER;}
\n  {return 0;}
.   {return yytext[0];}
%%


Output:

No comments:

Post a Comment

Featured post

Amazon Interview Process

On July 5, 1994, Jeff Bezos started the world's most "customer-centric" firm out of his garage in Bellevue, Washington. The A...