Program:
// Yacc Program: expr.y
%{
#include"stdio.h"
%}
%token DIGIT
%%
S : E '\n' {printf("%d\n",$1);return 1;}
;
E : E '+' T { $$ = $1 + $3 ;}
| T
;
T :T '-' FF { $$ = $1 - $3 ;}
| FF
;
FF :FF '/' FFF { $$ = $1 / $3 ;}
|FFF;
FFF :FFF '*' F { $$ =$1*$3 ;}
|F
;
F : '(' E ')' { $$ = $2 ;}
|DIGIT
;
%%
yylex()
{
int c;
c=getchar();
if(isdigit(c))
{
yylval=c-'0';
return DIGIT;
}
return c;
}
main()
{
printf("Enter the exp:");
yyparse();
}
Output:
nn@linuxmint ~ $ lex io.l
nn@linuxmint ~ $ yacc expr.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter the exp:5*(5+1)-9/2
26
nn@linuxmint ~ $
// Yacc Program: expr.y
%{
#include"stdio.h"
%}
%token DIGIT
%%
S : E '\n' {printf("%d\n",$1);return 1;}
;
E : E '+' T { $$ = $1 + $3 ;}
| T
;
T :T '-' FF { $$ = $1 - $3 ;}
| FF
;
FF :FF '/' FFF { $$ = $1 / $3 ;}
|FFF;
FFF :FFF '*' F { $$ =$1*$3 ;}
|F
;
F : '(' E ')' { $$ = $2 ;}
|DIGIT
;
%%
yylex()
{
int c;
c=getchar();
if(isdigit(c))
{
yylval=c-'0';
return DIGIT;
}
return c;
}
main()
{
printf("Enter the exp:");
yyparse();
}
Output:
nn@linuxmint ~ $ lex io.l
nn@linuxmint ~ $ yacc expr.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter the exp:5*(5+1)-9/2
26
nn@linuxmint ~ $
Find the best essays on is my friend's profile page. AI Talent Assessment Tool
ReplyDelete