lex program to implement a simple calculator.
/*lex program to implement a simple calculator.*/ %{ int op = 0,i; float a, b; %} %option noyywrap dig [0-9]+|([0-9]*)"."([0-9]+) add "+" sub "-" mul "*" div "/" pow "^" ln \n %% {dig} {compute();} {add} {op=1;} {sub} {op=2;} {mul} {op=3;} {div} {op=4;} {pow} {op=5;} {ln} {printf("\n The Answer :%f\n\n",a);} %% compute() { if(op==0) /* atof() is used to convert the ASCII input to float */ a=atof(yytext); else { b=atof(yytext); switch(op) { case 1:a=a+b; break; case 2:a=a-b; break; case 3:a=a*b; break; case 4:a=a/b; break; case 5:for(i=a;b>1;b--) a=a*i; break; } op=0; } } main() { yylex(); } Execution $flex cal.lex $ gcc lex.yy.c $ ./a.out 2+3 The Answer :5.000000 2.2/1.2 The Answer :1.833333 2.54-1.23 The Answer :1.310000 2/3 The Answer :0.666667