9. Program in YACC to evaluate an expression (simple calculator program for addition and subtraction, multiplication, division)

 

Program in YACC to evaluate an expression (simple calculator program for addition and subtraction, multiplication, division)

/*Program in YACC to evaluate an expression (simple calculator program for addition and
subtraction, multiplication, division).*/
File Name : calc10.y
%{
 #include<stdio.h>
int yylex(void);
int yyerror(char *);
%}

%token NAME NUMBER

%%
statement : NAME '=' expression
 | expression { printf("=%d\n",$1);}
 ;
expression:expression'+' NUMBER{$$ = $1+$3;}
 |expression '-' NUMBER {$$ = $1-$3;}
 |expression '*' NUMBER {$$ = $1*$3;}
 |expression '/' NUMBER { if ($3!=0){ $$ = $1/$3; }else { printf("Error: divide by Zero"); } }
 |NUMBER {$$=$1;}
 ;

%%
int main()
{
yyparse();
return 0;
}
int yyerror(char *s)
{
 printf("%s",s);
}

File Name : calc10.l
%{
 #include "y.tab.h"
 extern int yylval;
%}

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

// Output of the Above Program.
Program in YACC to evaluate an expression (simple calculator program for addition and subtraction, multiplication, division)
Program in YACC to evaluate an expression (simple calculator program for addition and
subtraction, multiplication, division)

Comments

Popular posts from this blog

Compiler Design

3. Lex program to find the length of the longest word

6. Lex program to count the number of words,small and capital letters, digits and special characters in a C file