Skip to content
Related Articles

Related Articles

Improve Article
Lex program to implement a simple Calculator
  • Last Updated : 30 Apr, 2019

Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

The commands for executing the LEX program are:

lex abc.l (abc is the file name)
cc lex.yy.c -efl

Let’s see LEX program to implement a simple calculator.


Input : 
Output :

Input : 
Output : 

Below is the implementation:

/*lex program to implement 
         - a simple calculator.*/
% {
  int op = 0,i;
  float a, b;
% }
dig [0-9]+|([0-9]*)"."([0-9]+)
add "+"
sub "-"
mul "*"
div "/"
pow "^"
ln \n
/* digi() is a user defined function */
{dig} {digi();} 
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{pow} {op=5;}
{ln} {printf("\n The Answer :%f\n\n",a);}
/* atof() is used to convert 
      - the ASCII input to float */
   case 1:a=a+b;
   case 2:a=a-b;
   case 3:a=a*b;
   case 4:a=a/b;
   case 5:for(i=a;b>1;b--)
main(int argv,char *argc[])
  return 1;


Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.


My Personal Notes arrow_drop_up
Recommended Articles
Page :