Exp5 Yacc and Lex
Exp5 Yacc and Lex
05
Name: Sanjay Gupta Batch: b1 Roll No. 16
1. Hello World:
%option noyywrap
%{
#include<stdio.h>
%}
%%
"hello world" printf("Hello World!\n");
. ;
%%
int main()
{
yylex();
return 0;
}
Output:
b
%option noyywrap
%{
#include<stdio.h>
%}
%%
[a-z] printf("LowerCase\n");
[A-Z] printf("Uppercase\n");
. ;
%%
int main()
{
yylex();
return 0;
}
Output:
%option noyywrap
%{
#include<stdio.h>
int lower=0;
int upper=0;
%}
%%
[a-z] { printf("LowerCase\n");lower++; }
[A-Z] { printf("Uppercase\n");upper++; }
\n { printf("\nNo. of uppercase letters=%d\nNo of lowercase letters=%d",upper,lower); }
. ;
%%
int main()
{
printf("Enter String : \n");
yylex();
return 0;
}
Output:
%option noyywrap
%{
#include<stdio.h>
int vowel=0;
int cons=0;
%}
%%
[aeiouAEIOU] { printf("vowel\n"); vowel++; }
[a-zA-Z] { printf("consonants\n"); cons++; }
\n { printf("vowel count=%d consonant count=%d",vowel,cons); }
. ;
%%
int main()
{
printf("Enter string:");
yylex();
return 0;
}
Output:
4. Identify tokens
%option noyywrap
%{
#include<stdio.h>
int token=0;
int i=0;
%}
%%
"if"|"else"|"while"|"dowhile"|"for"|"int"|"float"|"long"|"char"|"double"|"printf" { printf("Keyword\n");
token++; }
[A-Z|a-z]+ {printf("Variable\n"); token++; }
[0-9]+ {printf("Constant\n"); token++; }
[(|)|{|}|;|,] { printf("Special Characters\n"); token++; }
["]*[%A-z|A-za-z0-9]*["] {printf("String\n"); token++; }
[+|=|>|<] {printf("Operators\n"); token++; }
return 0;
}
Output:
5. Lines , words and Characters
%option noyywrap
%{
#include<stdio.h>
int lines=0;
int words=0;
int spaces=0;
int chars=0;
%}
%%
[A-Za-z] {chars++;}
\n {lines++;words++;}
%%
int main()
{
printf("Enter String : \n");
yylex();
return 0;
}
Output:
Calculator.l :
%option noyywrap
%{
#include<stdio.h>
float a=0;
float b=0;
int op=0;
%}
%%
[0-9]+ {
if(op==0)
a=atof(yytext);
else
{
b=atof(yytext);
switch(op)
{
case 1:a=a+b;
break;
case 2:a=a-b;
break;
case 3:a=a*b;
break;
case 4:a=a/b;
break;
}
op=0;
}
}
[+] {op=1;}
[-] {op=2;}
[*] {op=3;}
[/] {op=4;}
%%
int main()
{
printf("Enter the expression: ");
yylex();
return 0;
}
Output: