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..!!
13 comments :
want same calculator program to parse input concurrently and compare the result of
Concurrent parsing with serial parsing ( Using concurrent YACC parser)
how to compile and run this in linux?
the a.out file is not being created.
how to compile?
plz let me knw palindrome prgm
to compile make a file f.y and write above program
run yacc f.y
run cc y.tab.c -ly
@Anonymous
well 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
well 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!
how to write a program???????
@Anonymous
but why////
by zeeshan shamsudheen
what's use of num1:num1 num{$$ = $1*10 + $2;}
Really it is interesting
thank you
Post a Comment