Program to implement calculator using lex and YACC.

2 comments

Write a program to implement calculator using lex and YACC.


Program:

dharmik.y

%{
#include<stdio.h>
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
st: exp {printf("sum::%d",$$);}
    ;
exp: exp '+' exp {$$ = $1 + $3;}
    |exp '-' exp {$$ = $1 - $3;}
    |exp '*' exp {$$ = $1 * $3;}
    |exp '/' exp {$$ = $1 / $3;}
    |'('exp')' {$$ = $2;}                                   
    |NUMBER {$$ = $1;}
    ;
%%
int main()
{
        yyparse();
        return 0;
}
yyerror(char *s)
{
        printf("error:%s",s);
}

dharmik.l

%{
#include "y.tab.h"
#include<stdio.h>
extern int yylval;
%}
%%

[0-9]+ {yylval=atoi(yytext); return NUMBER;}
. {return yytext[0];}
[\t]+ ;
\n {return 0;} 
%%

Output:

2 comments :

  1. will this program run with out any errors...??

    ReplyDelete
    Replies
    1. This program is already performed in PC!! surely it will work.

      Delete