0% found this document useful (0 votes)
847 views

Compiler Design Lab Manual

The document contains the index and details of 13 experiments to be performed as part of a lab course. The experiments cover topics like identifying if a string is a keyword or not, counting keywords and operators in a file, counting character occurrences in a file, implementing a symbol table, using Lex programs to validate inputs like mobile numbers and URLs, and using Yacc programs for tasks like validating strings and evaluating expressions. Programs written in C are provided for tasks like validating dates, implementing a symbol table, and identifying keywords. Lex and Yacc programs are given for tasks like validating inputs and recognizing language constructs.
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)
847 views

Compiler Design Lab Manual

The document contains the index and details of 13 experiments to be performed as part of a lab course. The experiments cover topics like identifying if a string is a keyword or not, counting keywords and operators in a file, counting character occurrences in a file, implementing a symbol table, using Lex programs to validate inputs like mobile numbers and URLs, and using Yacc programs for tasks like validating strings and evaluating expressions. Programs written in C are provided for tasks like validating dates, implementing a symbol table, and identifying keywords. Lex and Yacc programs are given for tasks like validating inputs and recognizing language constructs.
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/ 24

INDEX

S.No. Content Page Number


1 Lab Ethics & Instructions 1-2
2 Marking/Assessment System 3
3 List of Experiments Prescribed by RTU 4
4 Lab Plan 5
5 A Brief about C, Lex and Yacc 6-16
Experiment 1: Introduction: Objective, scope and outcome of the
6 course. 17-19

Experiment 2: To identify whether given string is keyword or not.


7 20

8 Experiment 3: Count total no. of keywords in a file 22-23


9 Experiment 4: Count total no of operators in a file 24
Experiment 5 Count total occurrence of each character in a given
10 25-26
file
Experiment 6: a C program to insert, delete and display the entries
11 27-28
in Symbol Table.
Experiment 7: Write a LEX program to identify following: Valid
12 29-33
mobile number, Valid url, Valid identifier, Valid date, Valid time
13 Experiment 8: lex program to count blank spaces, words, lines 34
Experiment 9: lex program to count the no. of vowels and
14 35
consonants
Experiment 10 : YACC program to recognize strings aaab, abbb
15 36-37
using a^nb^n, where b>=0
Experiment 11: YACC program to evaluate an arithmetic
16 38-39
expression involving operators +,-,* and /
Experiment 12: YACC program to check validity of a strings
17 40-41
abcd, aabbcd using grammar a^nb^nc^md^m, where n , m>0
18 Experiment 13: C program to find first of any grammar 42-43
19 Multiple Choice Questions 44-48
20 Practical Exam Sample Paper 49
21 Text and Reference books 50
EXPERIMENT-2
AIM:

Program to find whether given string is keyword or not

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main()
{
char a[5][10]={"printf","scanf","if","else","break"}; char
str[10];
int i,flag;

clrscr();

puts("Enter the string :: ");


gets(str);

for(i=0;i<strlen(str);i++)
{
if(strcmp(str,a[i])==0)
{
flag=1;
break;
}
else
flag=0;
}
if(flag==1)
puts("Keyword");
else
puts("String");
getch();
}

20
EXPERIMENT-3
AIM:

Count total no. of keywords in a file. [Taking file from user]

PROGRAM:

#include<stdio.h>

#include<stdlib.h>
#include<string.h>
#include<ctype.h>
static int count=0;
int isKeyword(char buffer[]){

char keywords[32][10] =
{"auto","break","case","char","const","continue","default","do","double","else","enum","extern","fl
oat","for","goto","if","int","long","register","return","short","signed","sizeof","static","struct","switc
h","typedef","union","unsigned","void","volatile","while"};
int i, flag = 0;

for(i = 0; i < 32; ++i){


if(strcmp(keywords[i], buffer) == 0){
flag = 1;
count++;
break;
}
}

return flag;
}

int main(){
char ch, buffer[15] ;
FILE *fp;
int i,j=0;

fp = fopen("KESHAV3.C","r");

if(fp == NULL){
printf("error while opening the file\n");
exit(0);
22
}

while((ch = fgetc(fp)) != EOF){


if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;

if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);

}
printf("no of keywords= %d", count);
fclose(fp);

return 0;
}

23
EXPERIMENT-4

AIM:

Count total no of operators in a file. [Taking file from user] #include<stdio.h>

PROGRAM:

#include<stdlib.h>

#include<string.h>
#include<ctype.h>
static int count=0;
int main(){
char ch, buffer[15], operators[] = "+-*/%=";
FILE *fp;
int i;
clrscr();

fp = fopen("KESHAV3.C","r");

if(fp == NULL){
printf("error while opening the file\n");
exit(0);
}

while((ch = fgetc(fp)) != EOF){


for(i = 0; i < 6; ++i){
if(ch == operators[i]) {
printf("%c is operator\n", ch);
count++;
}
}

}
printf("no of operators= %d", count);
fclose(fp);

return 0;
}

24
EXPERIMENT-5

AIM:

Count total occurrence of each character in a given file. [Taking file from user]

PROGRAM:

#include <stdio.h>

#include <string.h>

#include<conio.h>

int main ()
{

FILE * fp;
char string[100];
int c = 0, count[26] = { 0 }, x;

fp = fopen ("deepa.txt", "r");


clrscr();

while (fscanf (fp, "%s", string) != EOF)

{ c=0;
while (string[c] != '\0')
{

/** Considering characters from 'a' to 'z' only and ignoring others. */

if (string[c] >= 'a' && string[c] <= 'z')


{

x = string[c] - 'a';

count[x]++;

25
c++;

}
}

for (c = 0; c <26 ; c++)


printf ("%c occurs %d times in the string.\n", c + 'a', count[c]);
return 0;

26
EXPERIMENT-6

AIM:

Write a C program to insert, delete and display the entries in Symbol Table.

PROGRAM:
//Implementation of symbol table
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("Given Expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol \t addr \t type");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c \t %d \t identifier\n",c,p);
x++;
j++;
27
}
else
{
ch=c;
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(ch);
add[x]=p;
d[x]=ch;
printf("\n %c \t %d \t operator\n",ch,p);
x++;
j++;
}}}}

28
EXPERIMENT-7

AIM:

Write a LEX program to identify following:

1. Valid mobile number


2. Valid url
3. Valid identifier
4. Valid date (dd/mm/yyyy)
5. Valid time (hh:mm:ss)

PROGRAM:

1.Valid mobile number


%{
/* Definition section */
%}

/* Rule Section */
%%

[1-9][0-9]{9} {printf("\nMobile Number Valid\n");}

.+ {printf("\nMobile Number Invalid\n");}

%%

// driver code
int main()
{
printf("\nEnter Mobile Number : ");
yylex();
printf("\n");
return 0;
}
int yywrap()
{
}

29
2. Valid url

%%

((http)|(ftp))s?:\/\/[a-zA-Z0-9]{2,}(\.[a-z]{2,})+(\/[a-zA-Z0-9+=?]*)* {printf("\nURL Valid\n");}

.+ {printf("\nURL Invalid\n");}

%%

void main() {

printf("\nEnter URL : ");

yylex();

printf("\n");

}
int yywrap()
{
}

30
3. Valid identifier

%%

^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");

// regex for invalid identifiers


^[^a - z A - Z _] printf("Invalid Identifier");
.;
%%

void main() {

printf("\nEnter Identifier: ");

yylex();

printf("\n");

}
int yywrap()
{
}

31
4. Valid date (dd/mm/yyyy)

%{
#include<stdio.h>
int i=0,yr=0,valid=0;
%}
%%
([0-2][0-9]|[3][0-1])\/((0(1|3|5|7|8))|(10|12))\/([1-2][0-9][0-9][-0-9]) {valid=1;}

([0-2][0-9]|30)\/((0(4|6|9))|11)\/([1-2][0-9][0-9][0-9]) {valid=1;}

([0-1][0-9]|2[0-8])\/02\/([1-2][0-9][0-9][0-9]) {valid=1;}

29\/02\/([1-2][0-9][0-9][0-9]) { while(yytext[i]!='/')i++;
i++;while(yytext[i]!='/')i++;i++;while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0');
if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;}

%%
void main()
{
yyin=fopen("new","r");
yylex();
if(valid==1) printf("It is a valid date\n");
else printf("It is not a valid date\n");
}
int yywrap()
{
return 1;
}

32
5.Valid time(hh:mm:ss)

%{
#include<stdio.h>
int i=0,yr=0,valid=0;
%}
%%
([0-2][0-9]:[0-6][0-9]\:[0-6][0-9]) {printf("%s It is a valid time\n",yytext);}

%%
void main()
{
yyin=fopen("new","r");
yylex();
}
int yywrap()
{
return 1;
}

33
EXPERIMENT-8

AIM:

Write a lex program to count blank spaces,words,lines in a given file.

PROGRAM:

%{
#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++;
%%
void main(void)
{
FILE *fp;
char f[50];
printf("enterfile name \n");
scanf("%s",f);
yyin= fopen(f,"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);
}
34
EXPERIMENT-9

AIM:

Write a lex program to count the no. of vowels and consonants in a C file.

PROGRAM:

%{

#include<stdio.h>
int vcount=0,ccount=0;
%}
%%
[a|i|e|o|u|E|A|I|O|U] {vcount++;}
[a-z A-Z (^a|i|e|o|u|E|A|I|O|U) ] {ccount++;}
%%
int main()
{
FILE *fp;
char f[50];
printf("enterfile name \n");
scanf("%s",f);
yyin= fopen(f,"r");
yylex();
printf("No. of Vowels :%d\n",vcount);
printf("No. of Consonants :%d\n",ccount);
return 0;
}
int yywrap()
{
}

35
EXPERIMENT-10

AIM:

Write a YACC program to recognize strings aaab,abbb using a^nb^n, where b>=0.

PROGRAM:

Gm.l

%{
#include "y.tab.h"
%}
%%
"a"|"A" {return A;}
"b"|"B" {return B;}
[ \t] {;}
\n {return 0;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Gm.y
%{
#include<stdio.h>
%}
%token A B
%%
stmt: S
;
S: A S B
|
;
%%
void main()
{
printf("enter \n");
yyparse();
printf("valid");
exit(0);
36
}
void yyerror()
{
printf("invalid ");
exit(0);
}

37
EXPERIMENT-11
AIM:

Write a YACC program to evaluate an arithmetic expression involving operators +,-,* and /.

PROGRAM:

Expr.l

%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);
return number;}
[\t] {;}
[\n] {return 0;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}

Expr.y
%{
#include<stdio.h>
int res=0;
%}
%token number
%left '+' '-'
%left '*' '/'
%%
stmt:expr {res=$$;}
;
expr:expr '+' expr {$$=$1+$3;}
|expr '-' expr {$$=$1-$3;}
|expr '*' expr {$$=$1*$3;}
|expr '/' expr {if($3==0)
exit(0);
else $$=$1/$3;}
38
|number
;
%%
void main()
{
printf(" enter expr\n");
yyparse();
printf("valid=%d",res);
exit(0);
}

void yyerror()
{
printf("invalid\n");
exit(0);
}

39
EXPERIMENT-12

AIM:

Write a YACC program to check validity of a strings abcd,aabbcd using grammar a^nb^nc^md^m,
where n , m>0

PROGRAM:

Grammer.y

%{
#include<stdio.h>
#include<stdlib.h>
int yyerror(char*);
int yylex();

%}
%token A B C D NEWLINE
%%
stmt: S NEWLINE { printf("valid\n");
return 1;
}
;
S: X Y
;

X: A X B
|
;
Y: C Y D
|
;
%%
extern FILE *yyin;
void main()
{
printf("enter \n");
do
{
yyparse();
}
while(!feof(yyin));

}
int yyerror(char* str)
{
40
printf("invalid ");
return 1;
}
Grammer.l

%{
#include"y.tab.h"
%}
%%
a|
A {return A;}
c|
C {return C;}
b|
B {return B;}
d|
D {return D;}
[ \t] {;}
"\n" {return NEWLINE;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}

41
EXPERIMENT-13
AIM:

Write a C program to find first of any grammar.

PROGRAM:

#include<stdio.h>

#include<ctype.h>
void FIRST(char );
int count,n=0;
char prodn[10][10], first[10];

void main()
{
int i,choice;
char c,ch;
printf("How many productions ? :");
scanf("%d",&count);
printf("Enter %d productions epsilon= $ :\n\n",count);
for(i=0;i<count;i++)
scanf("%s%c",prodn[i],&ch);
do
{
n=0;
printf("Element :");
scanf("%c",&c);
FIRST(c);
printf("\n FIRST(%c)= { ",c);
for(i=0;i<n;i++)
printf("%c ",first[i]);
printf("}\n");

printf("press 1 to continue : ");


scanf("%d%c",&choice,&ch);
}
while(choice==1);
}

void FIRST(char c)
{
int j;
42
if(!(isupper(c)))first[n++]=c;
for(j=0;j<count;j++)
{
if(prodn[j][0]==c)
{
if(prodn[j][2]=='$') first[n++]='$';
else if(islower(prodn[j][2]))first[n++]=prodn[j][2];
else FIRST(prodn[j][2]);
}
}
}

43

You might also like