Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

III Year- V Semester: B. Tech.

(Computer Science & Engineering)


Scheme & Syllabus of 4thYear B. Tech. (CS) for students admitted in Session 2017-18

5CS4-22: Compiler Design Lab

Credit: 1 Max. Marks: 50 (IA:30, ETE:20)


0L+0T+2P End Term Exam: 2 Hours

S.NO. NAME OF EXPERIMENT CO Mapped


1 To identify whether given string is keyword or not. CO1
2 Count total no. of keywords in a file. [Taking file from user] CO2
3 Count total no of operators in a file. [Taking file from user] CO3
4 Count total occurrence of each character in a given file. [Taking file from user] CO2
5 Write a C program to insert, delete and display the entries in Symbol Table. CO4
Write a LEX program to identify following:
a) Valid mobile number
6 b) Valid url CO5
c) Valid identifier
d) Valid date (dd/mm/yyyy)
7. Write a lex program to count blank spaces,words,lines in a given file. CO3
8. Write a lex program to count the no. of vowels and consonants in a C file. CO4
Write a YACC program to recognize strings aaab,abbb using a^nb^n, where
9. CO5
b>=0.
Write a YACC program to evaluate an arithmetic expression involving operators
10 CO5
+,-,*and /.
11 Write a C program to find first of any grammar. CO2
EXPERIMENT NO. 1

AIM:To identify whether given string is keyword or not.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char keyword[32][10]={"auto","double","int","struct","break","else","long",
"switch","case","enum","register","typedef","char",

"extern","return","union","const","float","short",

"unsigned","continue","for","signed","void","default",

"goto","sizeof","voltile","do","if","static","while"} ;

char string[10];

int flag=0,i;

printf("enter any string:");

gets(string);

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

if(strcmp(string,keyword[i])==0)

{
flag=1;

if(flag==1)

printf("%s is a keyword",string);

else

printf("%s is not a keyword",string);

getch();

CODE OUTPUT:
EXPERIMENT NO. 2

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

PROGRAM:
#include<stdio.h>
#include<string.h>
intmain(){
FILE *fp;
char str[30];
char
key[32][10]={"int","char","float","void","while","do","for","static","Extern","registe
r"};
char f=0,i,count=0;
fp=fopen("file1.txt","r");
while(fscanf(fp,"%s",str)!=EOF){
f=0;
for(i=0;i<10;i++){
if(!(strcmp(key[i],str))){
f=1;
}
}
if(f==1)
count++;
}
printf("%d",count);
return 0;
}

CODE OUTPUT:

File Name: file1.txt


Int =2
Float = 1
Void =1
Static = 1
Total = 5
EXPERIMENT NO. 3

AIM:Count total no of operators in a file. [Taking file from user]

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main() {
char ch;
int count=0;
FILE *fptr;
clrscr();
fptr=fopen("text.txt","w");
if(fptr==NULL) {
printf("File can't be created\a");
getch();
exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=getche())!='\r') {
fputc(ch,fptr);
}
fclose(fptr);
fptr=fopen("text.txt","r");
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF) {
count++;
printf("%c",ch);
}
fclose(fptr);
printf("\nThe number of characters present in file is: %d",count);
getch();
}

CODE OUTPUT:

File Name: sample1.txt


Number of Operator count = 12
EXPERIMENT NO. 4

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

PROGRAM:
#include <stdio.h>
#include <string.h>
intmain()
{
char string[100];
int c = 0, count[26] = {0}, x;

printf("Enter a string\n");
gets(string);

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]++;
}

c++;
}

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


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

return 0;
}
CODE OUTPUT:
EXPERIMENT NO. 5

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

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
#include<stdlib.h>
#define NULL 0
int size=0;
void Insert();
void Display();
void Delete();
intSearch(char lab[]);
void Modify();
structSymbTab
{
char label[10],symbol[10];
intaddr;
structSymbTab *next;};
structSymbTab *first,*last;
void main()
{
intop,y;
char la[10];
clrscr();
do
{
printf("\n\tSYMBOL TABLE IMPLEMENTATION\n");

printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.DELETE\n\t4.SEARCH\n\t5.MODIFY\n\
t6.END\n");
printf("\n\tEnter your option : ");
scanf("%d",&op);
switch(op)
{
case 1:
Insert();
break;
case 2:
Display();
break;
case 3:
Delete();
break;
case 4:
printf("\n\tEnter the label to be searched : ");
scanf("%s",la);
y=Search(la);
printf("\n\tSearch Result:");
if(y==1)
printf("\n\tThe label is present in the symbol table\n");
else
printf("\n\tThe label is not present in the symbol table\n");
break;
case 5:
Modify();
break;
case 6:
exit(0);
}
}while(op<6);
getch();
}
void Insert()
{
int n;
char l[10];
printf("\n\tEnter the label : ");
scanf("%s",l);
n=Search(l);
if(n==1)
printf("\n\tThe label exists already in the symbol table\n\tDuplicate can't be
inserted");
else
{
structSymbTab *p;
p=malloc(sizeof(structSymbTab));
strcpy(p->label,l);
printf("\n\tEnter the symbol : ");
scanf("%s",p->symbol);
printf("\n\tEnter the address : ");
scanf("%d",&p->addr);
p->next=NULL;
if(size==0)
{
first=p;
last=p;
}
else
{
last->next=p;
last=p;
}
size++;
}
printf("\n\tLabel inserted\n");
}
void Display()
{
inti;
structSymbTab *p;
p=first;
printf("\n\tLABEL\t\tSYMBOL\t\tADDRESS\n");
for(i=0;i<size;i++)
{
printf("\t%s\t\t%s\t\t%d\n",p->label,p->symbol,p->addr);
p=p->next;
}
}
intSearch(char lab[])
{
inti,flag=0;
structSymbTab *p;
p=first;
for(i=0;i<size;i++)
{
if(strcmp(p->label,lab)==0)
flag=1;
p=p->next;
}
return flag;
}
void Modify()
{
char l[10],nl[10];
intadd,choice,i,s;
structSymbTab *p;
p=first;
printf("\n\tWhat do you want to modify?\n");
printf("\n\t1.Only the label\n\t2.Only the address\n\t3.Both the label and address\n");
printf("\tEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n\tEnter the old label : ");
scanf("%s",l);
s=Search(l);
if(s==0)
printf("\n\tLabel not found\n");
else
{
printf("\n\tEnter the new label : ");
scanf("%s",nl);
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
strcpy(p->label,nl);
p=p->next;
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
case 2:
printf("\n\tEnter the label where the address is to be modified : ");
scanf("%s",l);
s=Search(l);
if(s==0)
printf("\n\tLabel not found\n");
else
{
printf("\n\tEnter the new address : ");
scanf("%d",&add);
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
p->addr=add;
p=p->next;
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
case 3:
printf("\n\tEnter the old label : ");
scanf("%s",l);
s=Search(l);
if(s==0)
printf("\n\tLabel not found\n");
else
{
printf("\n\tEnter the new label : ");
scanf("%s",nl);
printf("\n\tEnter the new address : ");
scanf("%d",&add);
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
strcpy(p->label,nl);
p->addr=add;
}
p=p->next;
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
}
}
void Delete()
{
int a;
char l[10];
structSymbTab *p,*q;
p=first;
printf("\n\tEnter the label to be deleted : ");
scanf("%s",l);
a=Search(l);
if(a==0)
printf("\n\tLabel not found\n");
else
{
if(strcmp(first->label,l)==0)
first=first->next;
else if(strcmp(last->label,l)==0)
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=NULL;
last=p;
}
else
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=q->next;
}
size--;
printf("\n\tAfter Deletion:\n");
Display();
}
}

CODE OUTPUT:
EXPERIMENT NO. 6

AIM:Write a LEX program to identify following:


a) Valid mobile number
b)Valid url
c)Valid identifier
d)Valid date (dd/mm/yyyy)

PROGRAM: (a)
/* Lex Program to check valid Mobile Number */
%{
/* Definition section */
%}

/* Rule Section */
%%
[1-9][0-9]{9} {printf("\nMobile Number Valid\n");}
.+ {printf("\nMobile Number Invalid\n");}
%%

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

CODE OUTPUT: (a)

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

// driver program
void main()
{
printf("\nEnter URL : ");
yylex();
printf("\n");
}

CODE OUTPUT: (b)

PROGRAM: (c)
/*lex code to determine whether input is an identifier or not*/
%{
#include <stdio.h>
%
}
/ rule section % %
// regex for valid identifiers
^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");
// regex for invalid identifiers
^[^a - z A - Z _] printf("Invalid Identifier");
.;
%%
main()
{
yylex();
}
CODE OUTPUT: (c)

PROGRAM: (d)
/* Lex program to check if a date is valid or not */

%{
/* Definition section */
#include<stdio.h>
inti=0, yr=0, valid=0;
%}

/* Rule Section */
%%
([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;}

%%

// driver code
main()
{
yyin=fopen("vpn.txt", "r");
yylex();
if(valid==1) printf("It is a valid date\n");
else printf("It is not a valid date\n");
}
intyywrap()
{
return 1;
}

CODE OUTPUT: (d)


EXPERIMENT NO. 7

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

PROGRAM:
%{
#include <stdio.h>
int c=0,w=0,s=0,l=0;
%}
word [^ \t\n,\.:]+
eol [\n]
blank [ ]
%%
{word} {w++; c=c+yyleng;}
{eol} {l++;}
{blank} {s++;}
%%

void main(intargc,char *argv[])


{
if (argc!=2)
{
printf("usage : ./a.out in.txt \n");
exit(0);
}
yyin=fopen(argv[1],"r");
yylex();
printf("no. of word %d \n",w);
printf("no. of char %d \n",c);
printf("no. of line %d \n",l);
printf("no. of space %d \n",s);
}
intyywrap()
{
return 1;
}

CODE OUTPUT:
CONTENTS OF IN.TXT FILE

my
name is xyz
and i am
from abc

no. of word 9
no. of char 24
no. of line 4
no. of space 5
EXPERIMENT NO. 8

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

PROGRAM:

CODE: ( vowel.l is the filename in which the below code is written)

%{

#include <stdio.h>

int vowel=0;

int cons=0;

%}

%%

[aeiouAEIOU] {vowel++;}

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

.+ {;}

%%

void main()

printf(“enter the string\n”);

yylex();

printf(“no. of vowels is : %d \n”, vowel);

printf(“no. of consonent is : %d \n”, cons);

}
intyywrap()

return 1;

CODE OUTPUT:

lexvowel.l

enter the string

my name is

no.of vowel is: 3

no.of consonant is: 5


EXPERIMENT NO. 9

AIM:Write a YACC program to recognize strings aaab,abbb using a^nb^n, where


b>=0.

PROGRAM:
Lex part :

%{
#include "y.tab.h"
%}
%%
a return A;
b return B;
.|\n return yytext[0];
%%
YaccPart :

%{
#include<stdio.h>
int valid=1;
%}
%token A B
%%
str:S'\n' {return 0;}
S:A S B
|
;
%%
main()
{
printf("Enter the string:\n");
yyparse();
if(valid==1)
printf("\nvalid string");
}
CODE OUTPUT:

Input: ab
Output: valid string

Input: aab
Output: invalid string

Input: aabb
Output: valid string

Input: abb
Output: invalid string

Input: aaabbb
Output: valid string
EXPERIMENT NO. 10

AIM:Write a YACC program to evaluate an arithmetic expression involving


operators +,-,* and /.

PROGRAM:
%
{
/* Definition section*/
#include "y.tab.h"
extern yylval;
%
}

%%
[0 - 9]
+
{
yylval = atoi(yytext);
return NUMBER;
}

[a - zA - Z] + { return ID; }
[\t] + ;

\n { return 0; }
. { returnyytext[0]; }

%%

%{
/* Definition section */
#include
%

% token NUMBER ID
// setting the precedence
// and associativity of operators
% left '+' '-'
% left '*' '/'
/* Rule Section */
%
%E:T
{

printf("Result = %d\n", $$);


return 0;

T : T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%

intmain()
{
printf("Enter the expression\n");
yyparse();
}

/* For printing error messages */


intyyerror(char* s)
{
printf("\nExpression is invalid\n");
}

CODE OUTPUT:
Input: 7*(5-3)/2
Output: 7

Input: 6/((3-2)*(-5+2))
Output: -2
EXPERIMENT NO. 11
AIM:Write a C program to find first of any grammar.

PROGRAM:

#include<stdio.h>
#include<ctype.h>
void FIRST(char[],char );
void addToResultSet(char[],char);
intnumOfProductions;
char productionSet[10][10];
main()
{
inti;
char choice;
char c;
char result[20];
printf("How many number of productions ? :");
scanf(" %d",&numOfProductions);
for(i=0;i<numOfProductions;i++)//read production string eg: E=E+T
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",productionSet[i]);
}
do
{
printf("\n Find the FIRST of :");
scanf(" %c",&c);
FIRST(result,c); //Compute FIRST; Get Answer in 'result' array
printf("\n FIRST(%c)= { ",c);
for(i=0;result[i]!='\0';i++)
printf(" %c ",result[i]); //Display result
printf("}\n");
printf("press 'y' to continue : ");
scanf(" %c",&choice);
}
while(choice=='y'||choice =='Y');
}
/*
*Function FIRST:
*Compute the elements in FIRST(c) and write them
*in Result Array.
*/
void FIRST(char* Result,char c)
{
inti,j,k;
char subResult[20];
intfoundEpsilon;
subResult[0]='\0';
Result[0]='\0';
//If X is terminal, FIRST(X) = {X}.
if(!(isupper(c)))
{
addToResultSet(Result,c);
return ;
}
//If X is non terminal
//Read each production
for(i=0;i<numOfProductions;i++)
{
//Find production with X as LHS
if(productionSet[i][0]==c)
{
//If X → ε is a production, then add ε to FIRST(X).
if(productionSet[i][2]=='$') addToResultSet(Result,'$');
//If X is a non-terminal, and X → Y1 Y2 … Yk
//is a production, then add a to FIRST(X)
//if for some i, a is in FIRST(Yi),
//and ε is in all of FIRST(Y1), …, FIRST(Yi-1).
else
{
j=2;
while(productionSet[i][j]!='\0')
{
foundEpsilon=0;
FIRST(subResult,productionSet[i][j]);
for(k=0;subResult[k]!='\0';k++)
addToResultSet(Result,subResult[k]);
for(k=0;subResult[k]!='\0';k++)
if(subResult[k]=='$')
{
foundEpsilon=1;
break;
}
//No ε found, no need to check next element
if(!foundEpsilon)
break;
j++;
}
}
}
}
return ;
}
/* addToResultSet adds the computed
*element to result set.
*This code avoids multiple inclusion of elements
*/
void addToResultSet(char Result[],char val)
{
int k;
for(k=0 ;Result[k]!='\0';k++)
if(Result[k]==val)
return;
Result[k]=val;
Result[k+1]='\0';
}
CODE OUTPUT:
RUBRICS EVALUATION

Performance Scale 1 Scale 2 Scale 3 Scale 4 Score


Criteria (0-25%) (26-50%) (51-75%) (76-100%) (Numerical)

Understandability Unable to Able to Able to Able to understand


understand understand understand the problem
Ability to analyse the the problem the problem completely
Problem and Identify problem. partially and completely but and able to provide
solution unable to unable to alternative solution
identify the identify the too.
solution solution
Logic Program Program logic is Program logic is Program logic is
logic is on the right track mostly correct, correct, with no
Ability to specify incorrect but has several but may contain known boundary
Conditions & control errors an occasional errors, and no
flow that are appropriate boundary error redundant or
for the or redundant or contradictory
contradictory conditions.
problem domain.
condition.
Debugging Unable to Unable to debug Able to execute Able to execute
Ability to execute /debug execute several errors. program with program
program several completely
warnings.
Correctness Program Program Program Program produces
Ability to code formulae does not approaches produces correct correct answers or
and algorithms that produce correct answers answers or appropriate results
reliably produce correct correct or appropriate appropriate for all inputs
answers or appropriate answers or results for most results for most tested.
results. appropriate inputs, but can inputs.
results for contain
most inputs. miscalculations
in some cases.
Completeness Unable to Unable to Able to explain Able to explain
Ability to demonstrate explain the explain the code code and the code and the
and deliver on time. code.and the and the code program was program was
code was submission was delivered within delivered on time.
overdue. late. the due date.
TOTAL

You might also like