Loading

Lex and Yacc Calculator

Lex and Yacc Program to Implement Simple Calculator

Lex File -


 %{
       #include<math.h>
       #include"y.tab.h"    //for left,right,up & down
%}
%%

[0-9]+|[0-9]*\.[0-9]+ {
                       yylval.p = atof(yytext);
                       return num;        //return nonterminal
                       }

sin {return SIN;}    //return token SIN to YACC
cos {return COS;}    //return token COS to YACC
tan return TAN;        //return token TAN to YACC
log return LOG;        //return token LOG to YACC
sqrt return SQRT;    //return token SQRT to YACC
[\t];
\n      return 0;
.       return yytext[0];


%%

Yacc File

 %{
       #include<stdio.h>
       #include<math.h>
%}

%union                //to define possible symbol types
{ double p;}
%token<p>num
%token SIN COS TAN LOG SQRT

/*Defining the Precedence and Associativity*/

%left '+','-'            //lowest precedence
%left '*','/'            //highest precedenc
%nonassoc uminu            //no associativity
%type<p>exp            //Sets the type for non - terminal

%%

/* for storing the answer */
ss: exp {printf("=%g\n",$1);}

/* for binary arithmatic operators */
exp :    exp'+'exp      { $$=$1+$3; }
       |exp'-'exp      { $$=$1-$3; }
       |exp'*'exp      { $$=$1*$3; }
       |exp'/'exp      {
                               if($3==0)
                               {
                                       printf("Divide By Zero");
                                       exit(0);
                               }
                               else $$=$1/$3;
                       }
       |'-'exp         {$$=-$2;}
       |'('exp')'      {$$=$2;}
       |SIN'('exp')'   {$$=sin($3);}
       |COS'('exp')'   {$$=cos($3);}
       |TAN'('exp')'   {$$=tan($3);}
       |LOG'('exp')'   {$$=log($3);}
       |SQRT'('exp')'  {$$=sqrt($3);}
       |num;
%%

/* extern FILE *yyin; */
main()
{
       do
       {
               yyparse();    /* repeatedly tries to parse the                 sentence until the i/p runs out */
       }while(1);

}

yyerror(s)            /* used to print the error message when an                 error is parsing of i/p */

char *s;
{
       printf("ERROR");
}

Click Here to Download Source Code with Executable Program

Bookmark the permalink.

One Response to Lex and Yacc Calculator





  1. Links provided above are NOT working and basically you will just waste your time. I've spent some hours looking for the real and complete ebook and guess what? I have already found it and will be sharing here!

    CLICK HERE NOW TO DOWNLOAD THE COMPLETE ebook

    CLICK HERE NOW TO DOWNLOAD THE COMPLETE ebook


    Y'all have a nice day and enjoy reading! Much love!!!


    ReplyDelete