Desk Calculator

// Lex file: desk.l

DIGIT [0-9]+\.?|[0-9]*\.[0-9]+

%%

[ ]
{DIGIT}    {yylval=atof(yytext);return NUM;}
\n|.             {return yytext[0];}

// Yacc file: desk.y 

%{
    #include<ctype.h>
    #include<stdio.h>
    #define YYSTYPE double
%}

%token NUM

%left '+' '-'
%left '*' '/'
%right UMINUS

%%

S         : S E '\n' { printf("Answer: %g \nEnter:\n", $2); }
           | S '\n'
           |
           | error '\n' { yyerror("Error: Enter once more...\n" );yyerrok; }
           ;
E         : E '+' E    { $$ = $1 + $3; }
           | E'-'E    { $$=$1-$3; }
           | E'*'E    { $$=$1*$3; }
           | E'/'E    { $$=$1/$3; }
           | '('E')'    { $$=$2; }
           | '-'E %prec UMINUS { $$= -$2; }
           | NUM        
           ;

%%

#include "lex.yy.c"

int main()
{
    printf("Enter the expression: ");
    yyparse();
}

Comments

Popular posts from this blog

A program to find FIRST of non-terminals of the given grammar

Write a context free grammar for structure of a english sentence, where a pronoun is followed by a verb and verb is followed by determiner. Determiner is followed by noun and noun can be followed by noun. Statement can begin with noun or a proper noun. **following program is written for example sentence"I prefer a morning flight from New Delhi".