You are on page 1of 4

Experimrnt no:

Date:

Complie Design Lab

Page no:

Aim: write the programs for lex tool.


program1:
%{
#include<stdio.h>
%}
%%
"int" printf("keyword\n");
"char" printf("keyword\n");
[a-zA-Z][a-zA-Z0-9]* printf("indentifier\n");
[0-9]+ printf("number");
[+*%=] printf("Operator\n");
"/*"[A-Za-z0-9]*"*/" printf("comment\n");
%%
output:
[14A95A0507@Linux ~]$ lex pgm1.l
[14A95A0507@Linux ~]$ gcc lex.yy.c -ll
[14A95A0507@Linux ~]$ ./a.out
int
keyword
char
keyword
a
indentifier
^A
0
number
+
Operator
^Z
[8]+ Stopped
./a.out
[14A95A0507@Linux ~]$

Aditya Engineering College

Rollno:14A95A0507

Experimrnt no:
Date:

Complie Design Lab

Page no:

program 2:
%{
#include<stdio.h>
int vowels=0;
int cons=0;
%}
%%
[aeiouAEIOU] {vowels++;}
[a-zA-Z] {cons++;}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter the string at end press^d\n");
yylex();
printf("number of vowels=%d\n number of constants=%d\n",vowels,cons);
}
output:
[14A95A0507@Linux ~]$ lex pgm2.l
[14A95A0507@Linux ~]$ gcc lex.yy.c -ll
[14A95A0507@Linux ~]$ ./a.out
Enter the string at end press^d
priyanka
number of vowels=3
number of constants=5
[14A95A0507@Linux ~]$

Aditya Engineering College

Rollno:14A95A0507

Experimrnt no:
Date:

Complie Design Lab

Page no:

program 3:
%{
#include<stdio.h>
int posinteger=0,neginteger=0,posfraction=0,negfraction=0;
%}
%%
[-][0-9]+ {neginteger++;}
[+][0=9]+ {posinteger++;}
[+]?[0-9]*\.[0-9]+ {posfraction++;}
[-][0-9]*\.[0-9]+ {negfraction++;}
%%
int yywrap()
{
return 1;
}
main(int argc,char *argv[])
{
if(argc!=2)
{
printf("usage:<./a.out><sourcefile>\n");
exit(0);
}
yyin=fopen(argv[1],"r");
yylex();
printf("no. of +ve integers=%d\n no.of -ve integers=%d\n no. of +ve fractions=%d\n no. of -ve fractions=
%d\n",posinteger,neginteger,posfraction,negfraction);
}
output:
[14A95A0507@Linux ~]$ cat sample
4
5
6
8.90
9.88
-9.099
+9.776
[14A95A0507@Linux ~]$
[14A95A0507@Linux ~]$ lex pgm3.l
[14A95A0507@Linux ~]$ gcc lex.yy.c -ll
[14A95A0507@Linux ~]$ ./a.out sample
4
5
6
no. of +ve integers=0
no.of -ve integers=0
no. of +ve fractions=3
no. of -ve fractions=1

Aditya Engineering College

Rollno:14A95A0507

Experimrnt no:
Date:

Complie Design Lab

Page no:

program 4:
%{
#include<stdio.h>
int c=0,w=0,s=0,l=0;
%}
WORD [^\t\n,\.:]+
EOL [\n]
BLANK [ ]
%%
{WORD} {w++;c=c+yyleng;}
{BLANK} {s++;}
{EOL} {l++;}
. {c++;}
%%
int yywrap()
{
return 1;
}
main(int argc,char *argv[])
{
if(argc!=2)
{
printf("Usage: <./a.out><source file>\n");
exit(0);
}
yyin=fopen(argv[1],"r");
yylex();printf("no. of characters=%d\n no. of words=%d\n no. of spaces=%d\n no.of lines=%d\n",c,w,s,l);
}
output:
[14A95A0507@Linux ~]$ cat sample2
priya
pinky
p
q
r
[14A95A0507@Linux ~]$
[14A95A0507@Linux ~]$ lex pgm4.l
pgm4.l:10: warning, rule cannot be matched
[14A95A0507@Linux ~]$ gcc lex.yy.c -ll
[14A95A0507@Linux ~]$ ./a.out sample2
no. of characters=13
no. of words=5
no. of spaces=0
no.of lines=7
[14A95A0507@Linux ~]$

Aditya Engineering College

Rollno:14A95A0507