Expecting to get a good job without studying hard is like expecting to win a marathon without running it.
--Your friends at LectureNotes

Compiler Design

by Avinash AlugoluAvinash Alugolu
Type: PracticalInstitute: Centurion university of Technology and Management Course: B.Tech Specialization: Computer Science EngineeringViews: 71Uploaded: 1 year ago

Share it with your friends

Suggested Materials

Leave your Comments


Avinash Alugolu
Avinash Alugolu
Write a lex program to count no of identifiers, keywords ,digits. %{ #include<stdio.h> int lines=0, words=0,s_letters=0,c_letters=0, num=0, spl_char=0,total=0; %} %% \n { lines++; words++;} [\t ' '] words++; [A-Z] c_letters++; [a-z] s_letters++; [0-9] num++; . spl_char++; %% main(void) { yyin= fopen("myfile.txt","r"); yylex(); total=s_letters+c_letters+num+spl_char; printf(" This File contains ..."); printf("\n\t%d lines", lines); printf("\n\t%d words",words); printf("\n\t%d small letters", s_letters); printf("\n\t%d capital letters",c_letters); printf("\n\t%d digits", num); printf("\n\t%d special characters",spl_char); printf("\n\tIn total %d characters..\n",total); } int yywrap() { return(1); }
LEX Program to identify Keywords and convert it into uppercase. %{#include<stdio.h> int i; %}keyword main|int|scanf|printf|if|else %% {keyword} { for(i=0;i<yyleng;i++) printf("%c",toupper(yytext[i])); } %% main() { yyin=fopen("num.c","r"); yylex(); } int yywrap() { return 1; } OutputLet num.c contains following program fragment. main() { int num; scanf("%d",&num); if(num%2)printf("Odd"); else printf("Even") } The output will be,
MAIN() { INT num; SCANF("%d",&num); IF(num%2)PRINTF("Odd"); ELSE PRINTF("Even") } Lex program to count number of vowels and consonanta %{ int v=0,c=0; %} %% [aeiouAEIOU] v++; [a-zA-Z] c++; %% main() { printf("ENTER INTPUT : \n"); yylex(); printf("VOWELS=%d\nCONSONANTS=%d\n",v,c); }
Lex program to count the type of numbers %{ int pi=0,ni=0,pf=0,nf=0; %} %% \+?[0-9]+ pi++; \+?[0-9]*\.[0-9]+ pf++; \-[0-9]+ ni++; \-[0-9]*\.[0-9]+ nf++; %% main() { printf("ENTER INPUT : "); yylex(); printf("\nPOSITIVE INTEGER : %d",pi); printf("\nNEGATIVE INTEGER : %d",ni); printf("\nPOSITIVE FRACTION : %d",pf); printf("\nNEGATIVE FRACTION : %d\n",nf); } Lex program to count the number of printf and scanf statements %{ #include "stdio.h"

Lecture Notes