Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

4.

To Study about Lexical Analyzer Generator(LEX) and Flex(Fast Lexical Analyzer)

/*Lex code to count total number of tokens */

%{

int n = 0 ;

%}

/* rule section */

%%

"while"|"if"|"else" {n++;printf("\t keywords : %s", yytext);}

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

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

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

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

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

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

. ;

%%

int yywrap(){ return 1; }

int main()

yylex();

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

}
5.Implement following programs using Lex.

A. Create a Lexer to take input from text file and count no of characters, no. of lines & no. of words.

/* DESCRIPTION/DEFINITION SECTION */

/* Lex program to count the number of lines, spaces and tabs */

%{

#include<stdio.h>

int lc=0,sc=0,tc=0,ch=0,wc=0; // GLOBAL VARIABLES

%}

/* RULE SECTION */

%%

[\n] { lc++; ch+=yyleng;}

[ \t] { sc++; ch+=yyleng;}

[^\t] { tc++; ch+=yyleng;}

[^\t\n ]+ { wc++; ch+=yyleng;}

%%

int yywrap(){ return 1; }

/* After inputting press ctrl+d */


// MAIN FUNCTION

int main(){

printf("Enter the Sentence : ");

yylex();

printf("Number of lines : %d\n",lc);

printf("Number of spaces : %d\n",sc);

printf("Number of tabs : %d\n",tc);

printf("Number of words : %d\n", wc);

printf("Number of characters : %d\n", ch);

return 0;

5B /*Write a LEX program to count the number of vowels and consonants in a given string */

%{

int vow_count=0;

int const_count =0;

%}

%%

[aeiouAEIOU] {vow_count++;}

[a-zA-Z] {const_count++;}

%%

int yywrap(){}

int main()
{

printf("Enter the string of vowels and consonants:");

yylex();

printf("Number of vowels are: %d\n", vow_count);

printf("Number of consonants are: %d\n", const_count);

return 0;

You might also like