Yacc Program to evaluate a given arithmetic expression
Prerequisite – Introduction to YACC
Problem: Write a YACC program to evaluate a given arithmetic expression consisting of ‘+’, ‘-‘, ‘*’, ‘/’ including brackets.
Examples:
Input: 7*(5-3)/2 Output: 7 Input: 6/((3-2)*(-5+2)) Output: -2
Lexical Analyzer Source Code:
% { /* Definition section*/ #include "y.tab.h" extern yylval; % } % % [0 - 9] + { yylval = atoi (yytext); return NUMBER; } [a - zA - Z] + { return ID; } [\t] + ; \n { return 0; } . { return yytext[0]; } % % |
Parser Source Code:
% { /* Definition section */ #include % } % token NUMBER ID // setting the precedence // and associativity of operators % left '+' '-' % left '*' '/' /* Rule Section */ % % E : T { printf ( "Result = %d\n" , $$); return 0; } T : T '+' T { $$ = $1 + $3; } | T '-' T { $$ = $1 - $3; } | T '*' T { $$ = $1 * $3; } | T '/' T { $$ = $1 / $3; } | '-' NUMBER { $$ = -$2; } | '-' ID { $$ = -$2; } | '(' T ')' { $$ = $2; } | NUMBER { $$ = $1; } | ID { $$ = $1; }; % % int main() { printf ( "Enter the expression\n" ); yyparse(); } /* For printing error messages */ int yyerror( char * s) { printf ( "\nExpression is invalid\n" ); } |
Output:
Notes:
Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation and result evaluation).
Steps for execution of Yacc program:
lex sample_lex_program.l yacc -d sample_yacc_program.y cc lex.yy.c y.tab.c -ll ./a.out
Recommended Posts:
- YACC program to implement a Calculator and recognize a valid Arithmetic expression
- YACC program for Conversion of Infix to Postfix expression
- Lex program to recognize valid arithmetic expression and identify the identifiers and operators
- YACC program to recognize strings of { anb | n≥5 }
- YACC program to recognize string with grammar { anbn | n≥0 }
- YACC program for Binary to Decimal Conversion
- YACC program to check whether given string is Palindrome or not
- YACC program which accept strings that starts and ends with 0 or 1
- Introduction to YACC
- Regular Expression Vs Context Free Grammar
- C program to detect tokens in a C program
- Lex Program to remove comments from C program
- Lex Program For checking a valid URL
- Lex program to identify the identifier
- Lex program to check whether a given number is even or odd
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.