arithmetic.l
//lex program
/* declaration section in this sections we will decleared the different value and include the header file which we are using in this program to run this program */
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
/* this sections is known as defined section in which we defined the rule and regulation of regular expression which will be going to accept or not */
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}
arithmatic.y
/* yacc program for soving arithmatic expression */
/* decleration section in this sections we will decleared the different value and include the header file which we are using in this program to run this program */
%{
#include<stdio.h>
int flag=0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
/* this sections is known as defined section in which we defined the rule and regulation of regular expression which will going to accept or not */
%%
ArithmeticExpression: E{
printf("\nResult=%d\n",$$);
return 0;
}
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%%
void main()
{
printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication, Divison, Modulus and Round brackets:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
}
how to run
save the file as above name
compile flex file "flex arithmetic.l"
compile yacc file " yacc -d arithmetic.y"
compile c file generated by flex and yacc "cc lex.yy.c y.tab.c -o arithmetic -ll "
run the obj file "./arithmetic"
Comments
Post a Comment