0% found this document useful (0 votes)
2 views4 pages

Wa0011.

Lex programming

Uploaded by

Tejaswini Phukan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Wa0011.

Lex programming

Uploaded by

Tejaswini Phukan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Program 1:

/*Lex program to take check whether the given number is even or odd */

%{
#include<stdio.h>
int i;
%}

%%

[0-9]+ {i=atoi(yytext);
if(i%2==0)
printf("Even");
else
printf("Odd");}
%%

int yywrap(){}

/* Driver code */
int main()
{

yylex();
return 0;
}

Program 2:
/* Lex Program to check whether a number is Prime or Not */

%{
/* Definition section */
#include<stdio.h>
#include<stdlib.h>
int flag,c,j;
%}

/* Rule Section */
%%
[0-9]+ {c=atoi(yytext);
if(c==2)
{
printf("\n Prime number");
}
else if(c==0 || c==1)
{
printf("\n Not a Prime number");
}
else
{
for(j=2;j<c;j++)
{
if(c%j==0)
flag=1;
}
if(flag==1)
printf("\n Not a prime number");
else if(flag==0)
printf("\n Prime number");
}
}
%%

// driver code
int main()
{
yylex();
return 0;
}

Program 3:
/*lex program to count words that are less than 5 and greater than 2 */

%{
int len=0, counter=0;
%}

%%
[a-zA-Z]+ { len=strlen(yytext);
if(len<10 && len>5)
{counter++;} }
%%

int yywrap (void )


{
return 1;
}

int main()
{
printf("Enter the string:");
yylex();
printf("\n %d", counter);
return 0;
}
Program 4:
LEX program to count the number of vowels and consonants in given string.

%{
int vow_count=0;
int const_count =0;
%}

%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%

main()
{
printf("Enter the string of vowels and consonents:");
yylex();
printf("Number of vowels are: %d\n", vow);
printf("Number of consonants are: %d\n", cons);
return 0;
}

Program 5:
/*Lex code to count total number of tokens */
Input: int p=0, d=1, c=2;

%{
int n = 0 ;
%}

// rule section
%%
//count number of keywords
"while"|"if"|"else" {n++;printf("\t keywords : %s", yytext);}

// count number of keywords


"int"|"float" {n++;printf("\t keywords : %s", yytext);}

// count number of identifiers


[a-zA-Z_][a-zA-Z0-9_]* {n++;printf("\t identifier : %s", yytext);}

// count number of operators


"<="|"=="|"="|"++"|"-"|"*"|"+" {n++;printf("\t operator : %s", yytext);}

// count number of separators


[(){}|, ;] {n++;printf("\t separator : %s", yytext);}

// count number of floats


[0-9]*"."[0-9]+ {n++;printf("\t float : %s", yytext);}

// count number of integers


[0-9]+ {n++;printf("\t integer : %s", yytext);}

. ;
%%

int main()

yylex();

printf("\n total no. of token = %d\n", n);

You might also like