Showing posts with label Expression Evaluation. Show all posts
Showing posts with label Expression Evaluation. Show all posts

Expression Evaluation - Yacc Program - Compiler Design

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 ~ $

Expression Evaluation YACC S6

%{
#include<stdio.h>
%}
%token DIGIT
%%
S    : E '\n' {printf("%d\n",$1);return 1;}
    ;
E    : E '+'    T    { $$ = $1 + $3 ; }
    | T
    ;
T    : T '*'    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();   
return 0;
}

Output:
students@ccflab-desktop:~$ yacc aa.y
students@ccflab-desktop:~$ gcc y.tab.c -ly
students@ccflab-desktop:~$ ./a.out
Enter the exp:2+5*5
27
students@ccflab-desktop:~$
Related Posts Plugin for WordPress, Blogger...