Calculator program using yacc and lex

cal.l

 

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

%option noyywrap

%%

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

cal.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();
}

yyerror (char * s)
{
printf (“% s \n”, s);
exit (1);
}

STEPS

$lex cal.l

$yacc cal.y

$cc  y.tab.c

$./a.out

Refer the video

 

 

Advertisements
This entry was posted in tech it !!. Bookmark the permalink.

7 Responses to Calculator program using yacc and lex

  1. shubhangi says:

    ok!!!!

  2. delina says:

    I need scientific calculator using lex and yacc

  3. rashmi gound says:

    its nnot working…..

  4. pradnya says:

    very nice
    i can not understand

  5. this program works
    %{
    #include
    #include
    #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();
    }

    yyerror (char * s)
    {
    printf (“% s \n”, s);
    exit (1);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s