Pages

Saturday, October 8

Calculator using YACC program



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'
--> 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:

  1. want same calculator program to parse input concurrently and compare the result of
    Concurrent parsing with serial parsing ( Using concurrent YACC parser)

    ReplyDelete
  2. how to compile and run this in linux?

    ReplyDelete
  3. the a.out file is not being created.

    ReplyDelete
  4. how to compile?

    ReplyDelete
  5. plz let me knw palindrome prgm

    ReplyDelete
  6. to compile make a file f.y and write above program
    run yacc f.y
    run cc y.tab.c -ly

    ReplyDelete
  7. @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.

    ReplyDelete
  8. @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.

    ReplyDelete
  9. does not work!

    ReplyDelete
  10. how to write a program???????

    ReplyDelete
  11. @Anonymous
    but why////
    by zeeshan shamsudheen

    ReplyDelete
  12. what's use of num1:num1 num{$$ = $1*10 + $2;}

    ReplyDelete
  13. Really it is interesting
    thank you

    ReplyDelete