Wa0011.
Wa0011.
ALGORITHM:
STEP 1: Define and include necessary ‘C’ declarations and token definitions
STEP 2: Define the translation rules and the input structure specifications for
the grammar
rules
STEP 3:Define the functions that are invoked in the rules
STEP 4:Read the input
STEP 5: If the given input matches with the defined rules , the yacc tool
executes the
respective actions.
STEP 6: End
PROGRAM:
//Program to implement calculator using yacc Tool
%{
#define YYSTYPE double
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
list: /*nothing*/
|list '\n'
|list expr '\n' {printf("\t%.8g\n",$2);}
;
expr: NUMBER {$$=$1;}
|expr '+' expr {$$=$1+$3;}
|expr '-' expr {$$=$1-$3;}
|expr '*' expr {$$=$1*$3;}
|expr '/' expr {$$=$1/$3;}
|'(' expr ')' {$$=$2;}
;
%%
#include<stdio.h>
#include<ctype.h>
char *progname;
int lineno=1;
main(argc,argv)
char *argv[];
{
progname=argv[0];
yyparse();
}
yylex()
{
int c;
while((c=getchar())==' '||c=='\t')
;
if(c==EOF)
return 0;
if(c=='.'||isdigit(c))
{
ungetc(c,stdin);
scanf("%lf",&yylval);
return NUMBER;
}
if(c=='\n')
lineno++;
return(c);
}
How to execute
Input:
5+6
Output:
11