Write a Program to Implement a Calculator and Recognize a Valid Arithmetic Expression Using Lex and Yacc.

 


Examples:

Input: 4+5 
Output: Result=9
Entered arithmetic expression is Valid

Input: 10-5
Output: Result=5
Entered arithmetic expression is Valid

Input: 10+5-
Output: 
Entered arithmetic expression is Invalid

Input: 10/5
Output: Result=2
Entered arithmetic expression is Valid

Input: (2+5)*3
Output: Result=21
Entered arithmetic expression is Valid

Input: (2*4)+
Output: 
Entered arithmetic expression is Invalid

Input: 2%5
Output: Result=2
Entered arithmetic expression is Valid 
Lexical Analyzer Source Code:

%{ 

#include<stdio.h> 

#include "y.tab.h" 

extern int yylval; 

%} 

%% 

[0-9]+ { 

yylval=atoi(yytext); 

return NUMBER; 

[\t] ; 

[\n] return 0; 

. return yytext[0]; 

%% 

int yywrap() 

return 1; 



Parser Source Code :

%{ 

#include<stdio.h> 
int flag=0; 
%} 

%token NUMBER 

%left '+' '-'

%left '*' '/' '%'

%left '(' ')'


%% 

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 not contain any space in between:\n");
yyparse(); 
if(flag==0) 
printf("\nEntered arithmetic expression is Valid\n\n"); 

yyerror(s)
char *s;
{
  printf("\nEntered arithmetic expression is Invalid\n\n"); 
  flag=1;
}

Output







Comments

Popular posts from this blog

Write A Program To Print Hello World Using Lex

Create a Student registration form using following tags form,input,textarea,button,select,optio. The registration form must consist of following information: first name,Middle name,last name, gender(use radio button),address,phone no,email id,hobbies(use checkbox),city,state,country,collage name (use dropdown menu).