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

3 comments:

  1. i was waitin' for this type of article and i have gained some useful information from this site. thanks for sharing this information.

    www.n8fan.net

    ReplyDelete
  2. I read your blog.I thought it was great.. Hope you have a great day. God bless.

    Camille
    www.imarksweb.org

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...