Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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 | exprterm | 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 exp term factor NUMBER

%type '+' '-' '*' '/' '(' ')'

%%

THE CODE I HAVE IS:

%{ #include #include #include %}

%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; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Fundamentals Of Database Systems

Authors: Sham Navathe,Ramez Elmasri

5th Edition

B01FGJTE0Q, 978-0805317558

More Books

Students also viewed these Databases questions

Question

Why do HCMSs exist? Do they change over time?

Answered: 1 week ago