0% found this document useful (0 votes)
3 views

Compiler Lab Experiment 2 Program

The document describes a simple lexical calculator implemented in C using Flex. It supports basic arithmetic operations such as addition, subtraction, multiplication, division, and exponentiation. The program processes user input equations and outputs the results until an invalid operation is encountered.

Uploaded by

abhishek21032004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Compiler Lab Experiment 2 Program

The document describes a simple lexical calculator implemented in C using Flex. It supports basic arithmetic operations such as addition, subtraction, multiplication, division, and exponentiation. The program processes user input equations and outputs the results until an invalid operation is encountered.

Uploaded by

abhishek21032004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

LEX CALCULATOR

%{
#include<stdio.h>
#include<stdlib.h>
int op=0;
float a,b,n,i;
void digit();
%}
digit [0-9]+|[0-9]*"."[0-9]+
add "+"
sub "-"
mul "*"
div "/"
pow "^"
end "\n"
%%
{digit} {digit();}
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{pow} {op=5;}
{end} {printf("result is %f ",a);printf("\nenter new equation\n");}
. {exit(0);}
%%
int main()
{
printf("enter the equation\n");
yylex();
}
int yywrap()
{
return(1);
}
void digit()
{
if(op==0)
{
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;

atof(yytext);
case 5:
i=1;
n=a;
while(i<b)
{
a=a*n;
i++;
}
break;
default:
printf("invalid operation\n");
}
op=0;
}
}

OUTPUT

lex lexcalculator.l
[cs2120@LabServer complier]$ cc lex.yy.c
[cs2120@LabServer complier]$ ./a.out
enter the equation
2+4
result is 6.000000
enter new equation
9-6
result is 3.000000
enter new equation
2*3
result is 6.000000
enter new equation
10/2
result is 5.000000
enter new equation
2^3
result is 8.000000

You might also like