Monday 25 April 2016

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)

1 comment:

  1. Excellent read, Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. 140 lbs to kg

    ReplyDelete