Wednesday, July 27, 2011

Recognize arithematic expression

Share Orkut


Lex program

%{
#include <stdio.h>
#include "y.tab.h"
%}
number        [0-9]+
flot         [0-9]*"."[0-9]+
identifier    [a-zA-Z][a-zA-Z0-9]*
errr     [0-9][a-zA-Z0-9]*
%%
{number} {    return number;    }
{flot} {    return number;    }
{identifier} {    return identifier;    }
{errr} {    return err; }
[ \t]+
\n  {    return(0); }
.    {    return (int) yytext[0];}
%%


Yacc program

%{
#include <stdio.h>
int f=0;
%}
%token number identifier err
%%
input:    /* empty string */
          | input exp
       |error {f=1;}
       ;
exp:      number
       |identifier
           | exp '+' exp            
           | exp '-' exp           
           | exp '*' exp            
           | exp '/' exp            
           | '-' exp 
           | exp '^' exp  
           | '(' exp ')'
     ;
%%
int main()
{
         printf("\nEnter an arithmetic expression:\n\n");
         yyparse();
         if(f==0)
            printf("Valid Expression \n");
         else
            printf("Invalid Expression\n");
         return 0;
}
int yywrap()
{
           return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}

2 comments:

  1. input: /* empty string */
    | input exp
    |error {f=1;}
    ;

    wat is it doing?

    ReplyDelete
    Replies
    1. Its a left recursion which specifies that our input may contain zero(0) or more number of expressions ie.(exp) and when there is error set flag=1.

      Delete