Thursday, 12 January 2017

Lex Programs 2



1. Program to recognize whether a given sentence is simpler or compound.


Sim.l
%{
#include<stdio.h>
int is_simple=1;
%}
%%
[a-zA-Z0-9]+[ \t\n]+[aA][nN][dD][ \t\n]+[a-zA-Z0-9]+ {is_simple=0;}
[a-zA-Z0-9]+[ \t\n]+[oO][rR][ \t\n]+[a-zA-Z0-9]+ {is_simple=0;}
[a-zA-Z0-9]+[ \t\n]+[bB][uU][tT][ \t\n]+[a-zA-Z0-9]+ {is_simple=0;}
. {;}
%%
main()
{
printf("Enter the sentence\n");
yylex();
if(is_simple==1)
{
printf("\nThe given sentence is simple\n");
}
else
{
printf("\nThe given sentence is compound\n");
}
}

 




2.  Program to recognize and count the number of identifiers in a given input file.



Ide.l
%{
#include<stdio.h>
int count=0;
%}
var ([a-z]|[0-9]|"_")+
id "_"*{var}
%x chk c2 c3
%%
^("int"|"float"|"char"|"double") BEGIN(chk);
<chk>" "+ BEGIN(c2);
<c2>[,] BEGIN(c3);
<c2>[ ]
<c2>{id} {count++;}
<c3>{id} {count++;}
<c3>","
<c3>[;] {BEGIN(INITIAL);}
.|\n
%%
main()
{
 yyin=fopen("in.c","r");
 yylex();
 printf("No. of identifier are:%d\n",count);
}

In.c
#include<stdio.h>
void main()
{
int d,e;
float   as ,   asd ;
printf("printf("b");");
d=e;
scanf("enter %d",&d);
}



3.Program to recognize a valid arithmetic expression and identify the identifiers and operators present. Print them separately

%{
#include<stdio.h>
int flag=1;
int op=0,dig=0,top=-1;
char st[10];
%}
digit [0-9]+
oper [+*/-]
%%
['('] {st[++top]='(';}
[')'] {flag=1;
            if((st[top]!='(') && (top!=-1))
            {
                        printf("\n Invalid Expression\n");
                        exit(0);
            }
            top--;
}
{digit} {dig++;}
{oper}/{digit} {op++;}
{oper}/['('] {op++;}
. {printf("\nInvalid Expression"); exit(0);}
%%
main()
{
 printf("\nEnter arithmetic expression\n");
 yylex();
 if(((op+1==dig) || (op==dig)) && (top==-1))
 {
  printf("\nValid Expression\n");
  printf("\nNo. of operators=%d\nno. of operands=%d\n",op,dig);
 }
 else
   printf("\nInvalid expression");
}
 





 Thank You For Reading.

Please Comment the queries and doubt
Also programs you require.



2 comments: