/* ARITHMETIC EXPRESSION EVALUATION */
Yacc program
%{
#include<stdio.h>
#include<stdlib.h>
int i;
%}
%token num alpha NL
%left '+''-'
%left '*''/'
%right '^'
%nonassoc UMINUS
%%
S:E NL {printf("The answer is
=%d\n",$$);exit(0);}
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|'-'E %prec UMINUS {$$=-$2;}
|'('E')'
{$$=$2;}
|E'^'E
{if($3==0)
$$=1;
else
{
$$=1;
for(i=1;i<=$3;i++)
$$=$$*$1;}
}
|num {$$=$1;}
;
%%
#include"lex.yy.c"
#include<stdio.h>
int main()
{
yyparse();
yylex();
return 1;
}
yyerror(char *s)
{
printf("\nError\n");
}
Lex program
%{
#include "y.tab.h"
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[ \t] ;
[\n] {return NL;}
. {return yytext[0];}
%%
OUTPUT
(2*3)/2+4-1
The answer is =6
(4*3)-(2*2)+5-1
The answer is =12






0 comments:
Post a Comment