Here is the Yacc program implementing a simple calculator:
%{
#include<stdio.h>
#include<ctype.h>
%}
%token num
%left '+''-'
%left '*''/'
%right '^'
%%
s:e'\n'{printf("%d",$1);}
e: e '+' e{$$=$1+$3;}
|e '-' e{$$=$1-$3;}
|e '*' e{$$=$1*$3;}
|e '/' e{$$=$1/$3;}
|e '^' e {
int i,j=$1;
for(i=1;i<$3;i++)
{
j=j*$1;
$$=j;
}
}
|'('e')'{$$=$2;}
|num1;
num1:num1 num{$$ = $1*10 + $2;}
|num
;
%%
yylex()
{
int c;
c=getchar();
if(isdigit(c))
{
yylval=c-'0';
return num;
}
return c;
}
int main()
{
yyparse();
return 1;
}
int yyerror()
{
return 1;
}
int yywrap()
{
return 1;
}
Illustration:
Let the Input be 2+5
Moving from first definition s:e'\n'
s --> move to DEF(e)
e: e '+' e is selected. Evaluate first 'e' ie e-->num1
num1 extracts the token (i.e, number here 2 is extracted and stored in $1)
Then '+' is extracted and stored in $2.
Then move to e--> num1, thus 5 is extracted and stored in $3.
Now add them and store result in $$.
Go back to S: e'\n' and print result (which is 'e' here..!!)
If you have any doubt regarding this post feel free to comment here.
Thank U..!!
For more Yacc programs click here..!!
want same calculator program to parse input concurrently and compare the result of
ReplyDeleteConcurrent parsing with serial parsing ( Using concurrent YACC parser)
how to compile and run this in linux?
ReplyDeletethe a.out file is not being created.
ReplyDeletehow to compile?
ReplyDeleteplz let me knw palindrome prgm
ReplyDeleteto compile make a file f.y and write above program
ReplyDeleterun yacc f.y
run cc y.tab.c -ly
@Anonymous
ReplyDeletewell useyacc -d filename.yand you need to also make a lex file and save it bylex filename1.l, then compile it by gcc lex.yy.c y.tab.c -ll and then use the expression 2+4 or something in linux terminal.
@Anonymous
ReplyDeletewell use for compiling yacc -d filename.y and you need to also make a lex file and save it by lex filename1.l , then compile it by gcc lex.yy.c y.tab.c -ll and then use ./a.out and then use expression 2+4 or something in linux terminal.
does not work!
ReplyDeletehow to write a program???????
ReplyDelete@Anonymous
ReplyDeletebut why////
by zeeshan shamsudheen
what's use of num1:num1 num{$$ = $1*10 + $2;}
ReplyDeleteReally it is interesting
ReplyDeletethank you