Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I am struggling with my Yacc Program. Here are the requirements: According t

ID: 3679240 • Letter: H

Question

Hi, I am struggling with my Yacc Program. Here are the requirements:

According to the following context-free grammar, write a yacc file as a integer calculator that can do +, -, *, /, and ^ with or without ( ).

commandexpr

exprexpr + term | expr–term | term

termterm * term2 | term / term2 | term2 |-factor

term2factor ^ term2 | factor

factor( expr ) | NUMBER

In order to run calculator on real numbers the following needs to be added in the definition section and then the rest of the program needs to be made to work on real numbers.

%token NUMBER

%union { double val;

char op; }

%type <val> exp term factor NUMBER

%type <op> '+' '-' '*' '/' '(' ')'

%%

THE CODE I HAVE IS:

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

%token NUMBER

%%

command : exp   {printf("%d ",$1);}
   ;

exp   : exp '+' term   {$$ = $1 + $3;}
   | exp "-" term   {$$ = $1 - $3;}
   | exp '^' term {$$ = pow($1,$3);}
   |'(' exp ')' term {$$ = $2;}
   | term   {$$ = $1;}
   ;

term   : term '*' factor   {$$ = $1 * $3;}
    | term '/' factor       {$$ = $1 / $3;}
   | factor    {$$ = $1;}
   ;

factor   : NUMBER   {$$ = $1;}
   | '(' exp ')'   {$$ = $2;}
   ;

%%

main()
{ return yyparse();
}

int yylex(void)
{ int c;
while((c = getchar()) == ' ');
if ( isdigit(c) ) {
    ungetc(c, stdin);
    scanf("%d",&yylval);
    return(NUMBER);
}
if ( c == ' ') return 0;
return(c);
}

int yyerror(char * s)
{ fprintf(stderr,"%s ",s);
return 0;
}

Explanation / Answer

/* Try this program for simple caluclator*/

%{
#include<stdio.h>
#include<ctype.h>
%}
%token num
%left '+''-'
%left '*''/'
%right '^'
%%
s:e' '{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;
}

Result:

Let the Input be 2+5

Moving from first definition s:e' '
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' ' and print result (which is 'e' here..!!)

Hope it will help you!!!!!!!!!11

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote