yacc program to implement arithmetic operators

 

 

Lex program

%{
#include<stdio.h>
#include<stdlib.h>
%}
%%
[0-9]+    {yylval=atoi(yytext);return (NUM);}
“+”|”-“|”*”|”/”|”\n”    {return yytext[0];}
%%

Yacc program

%{
#include<stdio.h>
#include<ctype.h>
int i=0;
%}
%token NUM
%left ‘+”-‘
%left ‘*”/’
%%
S:E ‘\n’    {printf(“result =%d”,(int)$$);}
;
E:E’+’E    {$$=$1+$3;}
|E’-‘E    {$$=$1-$3;}
|E’*’E    {$$=$1*$3;}
|E’/’E    {$$=$1/$3;}
|NUM    {$$=$1;}
;
%%
#include “lex.yy.c”
main()
{
yyparse();
}
int yywrap()
{}
int yyerror()
{}

Sample output

5+7

result=12

9-7

result=2

5*8

result=40

9/3

result=3

 

Leave a Reply

Your email address will not be published. Required fields are marked *