To write a yacc program to recognize a valid arithmetic expression that uses operator +,- ,* and /.
- Start the program.
- Write a program in the vi editor and save it with .l extension.
- In the lex program, write the translation rules for the operators =,+,-,*,/ and for the identifier.
- Write a program in the vi editor and save it with .y extension.
- Compile the lex program with lex compiler to produce output file as lex.yy.c. eg $ lex filename.l
- Compile the yacc program with yacc compiler to produce output file as y.tab.c. eg $ yacc โd arith_id.y
- Compile these with the C compiler as gcc lex.yy.c y.tab.c
- Enter an arithmetic expression as input and the tokens are identified as output.
com.|.txt
%{
/* This LEX program returns the tokens for the expression */
#include "y.tab.h"
%}
%%
"=" {printf("\n Operator is EQUAL");}
"+" {printf("\n Operator is PLUS");}
"-" {printf("\n Operator is MINUS");}
"/" {printf("\n Operator is DIVISION");}
"*" {printf("\n Operator is MULTIPLICATION");}
[a-zA-Z]*[0-9]* {
printf("\n Identifier is %s",yytext);
return ID; }
. return yytext[0];
\n return 0;
%%
int yywrap()
{
return 1;
}
com.y.txt
%{
#include <stdio.h>
/* This YACC program is for recognizing the Expression */
%}
%token A ID
%%
statement: A'='E
| E {
printf("\n Valid arithmetic expression");
$$=$1;
}
;
E: E'+'ID
| E'-'ID
| E'*'ID
| E'/'ID
| ID
;
%%
extern FILE*yyin;
int main() {
do {
yyparse();
}while(!feof(yyin)); }
yyerror(char*s)
{
}
A YACC program to recognize a valid arithmetic expression that uses operator +,-,* and / is executed successfully and the output is verified.