Lex Program to recognize a valid arithmetic expression

 

Lex program to recognize a valid arithmetic expression and to recognize the identifiers and operators present. Print them separately.

Problem definition:

Write a Lex Program to recognize a valid arithmetic expression. If the arithmetic expression is valid then recognize the identifiers and operators present in the expression and print identifiers and operators separately.

Structure of LEX Program:

%{
Definition section
%}

%%
Rules section
%%

User Subroutine section  

Click here to know – How to Compile & Run LEX / YACC Programs on Windows 8, 10, and 11?

Source Code to recognize a valid arithmetic expression and display operators and identifiers in it

%{
#include<stdio.h>
#include<string.h>
int flag=0,i=0,j,k=0;
char operand[20][20],oparator[20][20];
%}

%%
[a-zA-Z0-9]+  {flag++; strcpy(operand[i],yytext);  i++;}
[-+*/]	{flag--;  strcpy(oparator[k],yytext);    k++;}
%%

int main(int argc, char* argv[])
{
	printf("enter an arithmetic expression\n");
	yylex();
	
	if(flag!=1)
		printf("Invalid expression\n");
	else
	{
		printf("Valid expression\n");
		
		printf("The operands are\t");
		for(j=0;j<i;j++)
			printf("%s\t",operand[j]);
			
		printf("\nThe operators are\t");
		for(j=0;j<k;j++)
			printf("%s\t",oparator[j]);
			
		printf("\n");
	}
}

int yywrap( )
{
	return 1;
}

Output:

input.c is the input file for the program

maheshgh@maheshgh:~/LexYacc$ lex demo.l

maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c

maheshgh@maheshgh:~/LexYacc$ ./a.out

Enter an arithmetic expression

a+b*c

Valid expression

The operands are a b c

The operators are + *

maheshgh@maheshgh:~/LexYacc$ ./a.out

Enter an arithmetic expression

a+b*

Invalid expression

Summary:

This article discusses how to write a Lex Program to recognize a valid arithmetic expression and to recognize the identifiers and operators present. Print them separately. If you like the article, do share it with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds