0% found this document useful (0 votes)
2K views2 pages

Objective: Write A Lex Program To Implement Simple Calculator Code

This document provides code for a simple calculator program written in lex. The code defines patterns to match digits, operators, and newlines. When a digit is matched, the digit() function converts the text to a float and stores it in the variable a or b depending on whether an operator has already been seen. When an operator is matched, it sets the global variable op to indicate the operation. The digit() function then performs the calculation indicated by op before resetting op to 0. Main simply calls yylex to start lex processing and the program outputs the result.

Uploaded by

sushil.singh.c
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)
2K views2 pages

Objective: Write A Lex Program To Implement Simple Calculator Code

This document provides code for a simple calculator program written in lex. The code defines patterns to match digits, operators, and newlines. When a digit is matched, the digit() function converts the text to a float and stores it in the variable a or b depending on whether an operator has already been seen. When an operator is matched, it sets the global variable op to indicate the operation. The digit() function then performs the calculation indicated by op before resetting op to 0. Main simply calls yylex to start lex processing and the program outputs the result.

Uploaded by

sushil.singh.c
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

Objective: Write a lex program to implement simple calculator

Code:

%option noyywrap
%{
#include<stdio.h>
int op=0,i;
float a,b;
%}

dig [0-9]+|([0-9]*)"."([0-9]+)
add "+"
sub "-"
mul "*"
div "/"
ln "\n"

%%
{dig} {digit();}
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{ln} {printf("result is %f\n",a);}
%%

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;
}
op=0;
}
}
void main()
{
yylex();
}

Output:

Questions:

1- What is the full form of atof?


Ans: atof is a function in the C programming language that converts a string into a floating point
numerical representation. atof stands for ASCII to float. It is included in the C standard library header
file stdlib.h

2-What is yywrap?
Ans:Function yywrap is called by lex when input is exhausted. Return 1 if you are done or 0 if more
processing is required.

You might also like