More you share, more you have!!!

More you share, more you have!!!

LEX program to recognize a valid arithmetic expression

lex-program-arithmetic

Q.Write a program using LEX to recognize a valid arithmetic expression and to recognize the identifiers and operators present. Print them separately.

Source Code->  

%{

#include<stdio.h>

int a=0,s=0,m=0,d=0,ob=0,cb=0;

int flaga=0, flags=0, flagm=0, flagd=0;

%}

id [a-zA-Z]+

%%

{id} {printf("\n %s is an identifier\n",yytext);}

[+] {a++;flaga=1;}

[-] {s++;flags=1;}

[*] {m++;flagm=1;}

[/] {d++;flagd=1;}

[(] {ob++;}

[)] {cb++;}

%%

int main()

{

printf("Enter the expression\n");

yylex();

if(ob-cb==0)

{

printf("Valid expression\n");

}

else

{

printf("Invalid expression");

}

printf("\nAdd=%d\nSub=%d\nMul=%d\nDiv=%d\n",a,s,m,d);

printf("Operators are: \n");

if(flaga)

printf("+\n");

if(flags)

printf("-\n");

if(flagm)

printf("*\n");

if(flagd)

printf("/\n");

return 0;

}

Output:->

$lex p2a.l

$cc lex.yy.c –ll

$./a.out

Enter the expression

(a+b*c)

a is an identifier

b is an identifier

c is an identifier

[Ctrl-d]

Valid expression

Add=1

Sub=0

Mul=1

Div=0

Operators are: 

+

*

Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment