4A) Program to recognize a valid arithmetic expression that uses operators +, -, * and /. [VTU SS&OS]

vtu ss & os 4a
Code:
LEXX:
YACC:

Explanation:
This program will check whether an arithmetic expression is valid or not. See how,

Lex:
%{
#include "y.tab.h"
%}

Declaration section. Include y.tab.h for making lexer read the input symbol so that it can send tokens to Yacc parser.

%%
[0-9]+(\.[0-9]+)?     { return NUM;}
[a-zA-Z_][_a-zA-Z0-9]* { return ID; }
[\t] ;
\n return 0;
. return yytext[0];
%%


  • if input contains numbers, return NUM token to parser.
  • if input contains a identifier, return ID token to parser.
  • ignore \t tabspaces.
  • if newline is encountered, it means end of expression, so return 0 to terminate lexer execution.
  • any other character is returned as it is.


yywrap()

{}

yywrap() function is responsible for checking whether there are any more inputs. If no, then yywrap() tells program to end.

Yacc:
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token NUM  ID
%left '+' '-'
%left '*' '/'

declaration section. include all header files required.
define tokens which are getting returned from lexer.
assign precedence and associativity of operators. first defined ones will have least preference. left means left associativity, and right means right associativity.

%%
e : e '+' e
|   e '-' e
|   e '*' e
|   e '/' e
|   '('e')'
| NUM
| ID         ;
%%

This is grammar to examine the expression.
  • e is the grammar defined in multiple ways. If input exactly satisfies this grammar, then we return to main() succesfully, and print "Valid" in the main(). Else, yyerror gets called, and message "Invalid" gets printed.
  • Grammar is defined as, E ->e+e or e-e or e*e and so on including NUM and ID tokens.
  • This gets matched recursively as the input is read. (of course according to the precedence defined).
  • Grammar need not be explained I suppose. If at all you need explanation, look at the grammar in program 5A. That grammar is similar. Its explained there
main()
{
printf(" Type the Expression & Press Enter key\n");
yyparse();
printf(" Valid Expression \n");
}
yyerror()
{
printf(" Invalid Expresion!!!!\n"); exit(0);
}

main function. ask for expression. if calculated normally, display "valid expression".
Otherwise, yyerror() will be executed displaying "Invalid expression".
remember we are displaying the evaluated answer in the grammer itself, when 'e' is valid.

He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!

Sharing is sexy!

Related Articles

Share your views about this article!