System Programming and Compiler Design
Subject Code: CSPC 421
DR. B. R. AMBEDKAR
NATIONAL INSTITUTE OF TECHNOLOGY-JALANDHAR
Department Of Computer Science and Engineering
Submitted to: Submitted by:
Dr Somesula Manoj Kumar K.Navya
Assistant Professor CSE Section: A Group: 3
Roll No: 20103081
Lab 3
1.Write a lex code to print “hello” message on matching a string “HI” and print “wrong
message”
%{
#include<stdio.h>
%}
%%
"HI" { printf("Hello\n");}
. { printf("wrong message\n");}
%%
int yywrap(){}
int main()
{
yylex();
return 0;
}
Output
2. Write a lex code to match odd or even number from input
%{
#include<stdio.h>
%}
%%
[0-9]+ {
int num = atoi(yytext);
if (num % 2 == 0) {
printf("%d even\n", num);
} else {
printf("%d odd\n", num);
}
}
. { printf("Invalid input\n");}
%%
int yywrap(){}
int main()
{
yylex();
return 0;
}
Output
3. Write a lex code to identify vowels and consonants in given input string
%{
#include<stdio.h>
%}
%%
[aAeEiIoOuU] {
printf("%c vowel\n", yytext[0]);
}
[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ] {
printf("%c consonant\n", yytext[0]);
}
. { printf("%c is not a letter\n", yytext[0]); }
%%
int yywrap(){}
int main()
{
yylex();
return 0;
}
output
4. Write a lex code to count and print number of lines, space, tabs, characters in given
input string
%{
#include<stdio.h>
int sc=0,lc=0,cc=0,wc=0,tc=0;
%}
%%
\n { lc++;}
\t { tc++; }
\s { sc++;}
. { cc++;}
%%
int yywrap( ){}
int main()
{
yylex();
printf("\nThe number of lines=%d\n",lc);
printf("The number of spaces=%d\n",sc);
printf("The number of characters are=%d\n",cc);
printf("The number of tabs are=%d\n",tc);
return 0;
}
output