You are on page 1of 7

1

COMPILER CONSTRUCTION(CS-636)
(LECTURE 11-12)

______________________________________________________
GIMS- PMAS Arid Agriculture University, Gujrat Campus
2

Flex Examples
%{ } 3
#include<stdio.h> main()
int Upper=0; {
int Lower=0; extern FILE *yyin;
%} printf("Enter a string\n");
yyin();
%% yylex();
[A-Z] {printf("%s Uppercase\t", printf("abc: %s" , Upper);
yytext);Upper++;} }
[a-z] {printf("%s Lowercase\t",
yytext);Lower++;}

%%

int yywrap()
{
return 1;
%{ {ID} printf( "An identifier: %s\n",
#include <math.h> yytext );
#include <stdio.h> 4
"+"|"-"|"*"|"/" printf( "An operator:
%} %s\n", yytext );
DIGIT [0-9] "//"[^}\n]* /* eat up one-line
ID [a-z][a-z0-9]* comments */
%option noyywrap [ \t\n]+ /* eat up whitespace */
%% . printf( "Unrecognized character:
{DIGIT}+ { %s\n", yytext );
printf( "An integer: %s (%d)\n", %%
yytext, main( )
atoi( yytext ) ); {
} yylex();
{DIGIT}+"."{DIGIT}* { }
printf( "A float: %s (%g)\n", yytext,
atof( yytext ) );
}
if|then|begin|end|procedure|function
{
printf( "A keyword: %s\n", yytext
);
}
%{
#include<stdio.h>
int no; { 5
%} printf("No of digits=%d",no);
%%
[a-z] {printf("%s Is a Small Letter\n", }
yytext);}
[A-Z] {printf("%s Is a capital Letter\n",
yytext);} }
[0-9] {printf("%s Is a numeric data \n",
yytext);}
%%
int yywrap()
{
return 1;
}

main()
{
printf("Enter a Character");
int tc= yylex();
while (tc!=0)
%{
#include<stdio.h>
%} 6
%%
"int"|"if"|"else"|"while"|"do"|"switch"|
"case" {printf("Keyword");}
[a-zA-Z][a-z|0-9]* {printf("Identifier");}
[0-9]* {printf("Number");}
"!"|"@"|"*"|"&"|"^"|"%"|"$"|"#"
{printf("Special Character");}
. {printf("invalid data");}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter a string of data\n");
yylex();
}
%{
#include<stdio.h>
int vowel=0; 7
int cons=0;
%}
%%
"a"|"e"|"i"|"o"|"u"|"A"|"E"|"I"|"O"|"U
" {printf("is a VOWEL");vowel++;}
[a-zA-z] {printf("Is a
Consonant");cons++;}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter String\n");
yylex();
}

You might also like