/*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