0% found this document useful (0 votes)
1K views

Compiler Design Practical File

The document describes a program that generates intermediate code forms like quadruples and triples from input strings. It takes multiple strings as input from the user, checks the length of each string, and rearranges the characters to generate the quadruples form for strings of length more than 4 and keeps the original string for others. It then prints the generated quadruples.

Uploaded by

park domain
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)
1K views

Compiler Design Practical File

The document describes a program that generates intermediate code forms like quadruples and triples from input strings. It takes multiple strings as input from the user, checks the length of each string, and rearranges the characters to generate the quadruples form for strings of length more than 4 and keeps the original string for others. It then prints the generated quadruples.

Uploaded by

park domain
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/ 43

University Institute of Technology

Rajiv Gandhi Proudyogiki Vishwavidyalaya


Bhopal

(SESSION 2011-2012)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Practical File: Compiler Design

Submitted to Submitted By:


Mr. Mahesh Parmar Manish Kumar
Chouriya
Roll No. 0101cs081025
INDEX
PAGE EXPERIMENT DATE REMARK
1. Write a Program for lexical Analyzer.

2. Write a Program for Syntax Analyzer.

3. Develop a recursive descent parser.

4. Write a program for generating quadruples form and triples


form for various intermediate code forms.

5. Write a program to generate the intermediate code in the form


of polish notation.

6. Write a program to perform operations on stack.

7. Write a program to calculate the first and follow of the given


grammar.

8. Write a program to simulate heap storage allocation strategy.

9. Given any intermediate code form implement code


optimization techniques.

10. Write a lex program to convert the substring abc to ABC from
the given input string.

11. Write a lex program to find out total number of vowels and
consonants from the given input string.

12. Write a lex program to identify the capital strings from the
given input string.

2
1) Write a Program for lexical Analyzer.

Solution:-

#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main ()
{
int id=0,addop=0,subop=0,multop=0,divop=0,semicolon=0,number=0,assignop=0;
char *ptr;
clrscr();
cout<<"\t\t\t*************LEXICAL ANALYSER**************\t\t\t";
cout<<"\nEnter The Expression: ";
gets(ptr);
cout<<endl;
while(*ptr!='\0')
{
if((*ptr>=48)&&(*ptr<=57))
{
while((*ptr>=48)&&(*ptr<=57))
{
ptr++;}
printf("");
number=number+1;
}
if((*ptr>=65)&&(*ptr<=90)||(*ptr>=97)&&(*ptr<=122))
{
while((*ptr>=65)&&(*ptr<=90)||(*ptr>=97)&&(*ptr<=122)||(*ptr>=48)&&(*ptr<=57
))
{
ptr++;}
id++;
}
if(*ptr==61)
{
printf("%c Assignment\n",*ptr);
assignop++;}
if(*ptr==43)
{
printf("%c Add\n",*ptr);
addop++;

3
}
if(*ptr==45)
{
printf("%c Subtract\n",*ptr);
subop++;
}
if(*ptr==42)
{printf("%c Multiplication\n",*ptr);
multop++;
}
if(*ptr==47)
{
printf("%c Divide\n",*ptr);
divop++;
}
if(*ptr==59)
{printf("%c semicolon\n",*ptr);
semicolon++;
}
ptr++;
}
cout<<ptr;
printf("\n The Given Expression Contains Following Operations : \n\n Identifier: %d\n
Number: %d\n Add Operation: %d\n Multiplication Operation: %d\n Assignment
Operation: %d\n Semicolon: %d\n Divide Operation: %d\n Substract Operation:
%d",id,number,addop,multop,assignop,semicolon,divop,subop);
getch();
}

Output:-

*************LEXICAL ANALYSER**************

Enter the Expression: A=b*c+d

= Assignment
* Multiplication
+ Add

The Given Expression Contains Following Operations:

Identifier: 4

4
Number: 0
Add Operation: 1
Multiplication Operation: 1
Assignment Operation: 1
Semicolon: 0
Divide Operation: 0
Substract Operation: 0

5
2) Write a Program for Syntax Analyzer.

Solution:-

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main()
{
int ans,i;

char*all_key[]={"int","char","float","double","auto","const","default","extern","far","
long","near","register","short","signed","static","unsigned","void","break","case","co
ntinue","do","else","enum","for","goto","if","return","struct","switch","typedef","un
ion","while"};
char input_key[10];
clrscr();
cout<<"Enter the keyword:";
cin>>input_key;

for(i=0;i<32;i++)
{
ans=strcmp(input_key,all_key[i]);
if(ans==0)
{
cout<<"Correct keyword";
getch();
exit(0);
}
}
cout<<"\n incorrect keyword!!";
getch();
exit(0);
}

Output:-

Enter the keyword: float


Correct keyword

6
3) Develop a Recursive Descent Parser.

Solution:-

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 128
#define NONE -1
#define EOS ‘\0’
#define NUM 257
#define KEYWORD 258
#define ID 259
#define DONE 260
#define MAX 999
char !exemes[MAX];
char buffer[SIZE];
int lastchar = -1;
int lastentry = 0;
int tokenval=DONE;
int lineno=1;
int lookahead;
struct entry{
char *lexptr;
int token;
}symtable[100];
struct entry keywords[ ]=
{“if”,KEYWORD,”else”,KEYWORD,
“for”,KEYWORD,
“int”,KEYWORD,”float”,KEYWORD,”double”,KEYWORD,”char”,KEYWORD,
“struct”,KEYWORD,
“return”,KEYWORD,
0,0};
Void Error_Message(char *m)
{
fprintf(stderr, ”line %d: %s \n”, lineno,m));
exit(1);
}
int look_up(char s[ ])
{
int k;

7
for(k=lastentry;k.>0;k=k-1)
if(strcmp(symtable[k].lexptr,s)= =0)
return k;
return 0;
}
{
int len;
len = strlen (s);
if(lastentry+1> = MAX)
error_message(“symbol table is full”)’
if (lastchar + len +1 = MAX )
error_message(“lexemes array is full”);
lastentry = lastentry +1;
symtable[lastentry].token = toksymtable[lastentry].lexptr = & lexemes [lastchar + 1];
lastchar = lastchar + len + 1;
strcpy(symtable[lastentry].lexptr,s);
return lastentry;
}
void initialize()
{
struct entry *ptr;
for(ptr = keywords;ptr->token;ptr++)
insert(ptr->lexptrl.ptr->token);
}
int lexer()
{
int t;
int val, i = 0;
while(1)
{
t= getchar();
if(t = = ‘ ‘|| t = = ‘\t’)

else if (t= = ‘\n’)


lineno = lineno=1;
else if (isdigit(t))
{
ungetc(t,stdin);
scanf(“%d”,& tokenval);
return NUM;
}
else if(isalpha(t))
{

8
while(isalnum(t))
{
buffer[i] = t;
t = getchar();
i = i+1;
if(i> =SIZE) error_message(“compiler error”);

}
buffer[i]=EOS;
if (t! = EOF)
ungetc(t,stdin);
val = look_up(buffer);
if(val = =0) val = insert(buffer,ID);
tokenval = val;
return symtable[val].token;
}
else if(t= =EOF)
return DONE;
else
{
tokenval= NONE’
return t;
}
}
}
void match(int t)
{
if(lookahead= =t)
lookahead=lexer();
else
error_message(“syntax error”);
}
void display(int t,int tvl)
{
if(t = =’+’!!t= =’-’!!t= =’*’!!t= =’/’)
printf(“\n Arithmatic Operater :%c”,t);
else if(t==NUM)
printf(“\n Mumber : %d”,tval);
else if(t==ID)
printf(“\n Identifier : %s”,symtable[tval].lexptr);
else
printf(“\n token %d tokenval %d”,t,tokenval);
}

9
void F()
{
void E( );
switch(lookahead)
{
case’(‘:
Match(‘(‘);
E( );
Match(‘)’);
break;
case NUM:
display(NUM,tokenval);
Match(NUM);
break;
case ID:
display(ID,tokenval);
Match(ID);
break;
default:
Error_Message(“Syntax Error”);
}
}
void t( )
{
int t;
F();
While(1)
{
Switch(lookahead)
{
case’*’:t=lookahead;
Match(lookahead);
F();
Display(t,NONE);
continue;
case’/’:t=lookahead;
Match(lookahead);
F();
display(t,NONE);
continue;
default;
return;
}

10
}
}
void E()
{
int t;
T();
while(1)
{
switch(lookahead)
{
Case’+:t =lookahead;
Match(lookahead);
T();
display(t.NONE);
continue;
case'-':t=lookahead;
Match(lookahead);
T();
display(t.NONE);
continue;
default:
return;
}
}
}
void parser()
{
lookahead=lexer();
while(lookahead!=DONE)
{
E();
Match(';');
}
}

void main()
{
char ans;
clrscr();
printf("\n\t\t Program for Recursive Descent Parsing \n\n");
Initialize();
printf("\n Enter the expression ");
printf("And place ;at the end");

11
printf("\nPress cntrl Z to terminate...\n");
parser();
}

Output:-

Program For recursive Descent parsing

Enter the expression And place ;at the end


Press Cntrl Zto terminate...
2+3*4;

Number:2
Number:3
Number:4
Arithmetic Operator: *
Arithmetic Operator: +
2+3*4+5;

Number:2
Number:3
Number:4
Arithmetic Operator: *
Arithmetic Operator: +
Number:5
Arithmetic Operator: +
a-b;

Indentifier: a
Indentifier: b

Arithmetic Operator: -
+1;
line 7: Syntax Error

12
4) Write a program for generating quadruples form and triples form for
various intermediate code forms.

Solution:-

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char arr[10][10],a[10][10];
int i,n,x[10];
cout<<"Enter the No. of Strings:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter the "<<i+1<<"String:";
cin>>arr[i];
}
for(i=0;i<n;i++)
{
x[i]=strlen(arr[i]);
if(x[i]>4)
{
a[i][0]=arr[i][0];
a[i][1]=arr[i][3];
a[i][2]=arr[i][2];
a[i][3]=arr[i][4];
}
else
{
a[i][0]=arr[i][0];
a[i][1]=arr[i][1];
a[i][2]=arr[i][2];
}}
cout<<"The Quadrapules are:";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i][0];
cout<<"\t"<<a[i][1];
cout<<"\t"<<a[i][2];
cout<<"\t"<<a[i][3];

13
cout<<"\n";
}
if(x[i]>4)
{
a[i][0]=arr[i][3];
a[i][1]=arr[i][2];
a[i][2]=arr[i][4];
}
else
{
a[i][0]=arr[i][1];
a[i][1]=i-1;
}
cout<<"the Triples are:";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i][0];
cout<<"\t"<<a[i][1];
cout<<"\t"<<a[i][2];
cout<<"\n";
}
getch();
}

Output:-

Enter the No. of Strings:2


Enter the 1 String:t=a+b
Enter the 2 String:c=t
The Quadrapules are:
t + a b

c = t
the Triples are:
+ a b

= t

14
5) Write a program to generate the intermediate code in the form of polish notation.

Solution:-

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct stack
{
char s[30];
int top;
}st;
void main()
{
char input[30];
void input_to_code(char infix[30]);
clrscr();
prntf("\n Enter an input in the form of expression");
scanf("%s",input);
input_to_code(input);
getch();
}
void input_to_code(char input[30])
{
st.top=-1;
st.s[st.top]=’$’;
char polish[30];
int I,j;
char ch;
int instack(char ch);
int incoming(char ch);
void push(char item);
char pop();
j=0;
strrev(input);
for(i=0;input[i]!=’\0’;i++)
{
ch=input[i];
while(instack(st.s[st.top])>incoming(ch))
{

15
polish[j]=pop();
j++;
}
If(instack(st.s[st.top])!-incoming(ch))
push(ch);
else
pop();
}
while((ch=pop())!=’$’)
{
polish[j]=ch;
j++;
}
polish[j]=’\0’;
strrev(polish);
printf(“\n The polish notation is %s”,polish);
}
int instack(char ch)
{
int priority;
switch(ch)
{
case')':priority=0;
break;
case'+':
case'-':priority=1;
break;
case'*':
case'/':priority=3;
break;
case'^':priority=6;
break;
case'$':priority=-1;
break;
default:priority=8;//when it is operand
break;
}
return priority;
}
int incoming(char ch)
{
int priority;
switch(ch)

16
{
case'+':
case'-':priority=2;
break;
case'*':
case'/':priority=4;
break;
case'^':priority=5;
break;
case'(':priority=0;
break;
case')':priority=9;
break;
default:priority=7://when it is operand
}
return priority;
}
void push(char item)
{
st.top++;
st.s[st.top]=item;
}
char pop
{
char e;
e=st.s[st.top];
st.top--;
return e;
}

Output:-

Enter an input in the form of expression (a+b)*(c-d)

The polish notation is *+ab-cd

17
6) Write a program to perform operations on stack.

Solution:-

# include<iostream.h>
# include<process.h>
# include<conio.h>
# define SIZE 20

class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}

int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}

void stack::push(int i)
{
if(!isfull())
{
a[tos]=i;
tos++;
}
else
{

18
cout<<"Stack overflow error ! Possible Data Loss !";
}
}
int stack::pop()
{
if(!isempty())
{
return(a[--tos]);
}
else
{
cout<<"Stack is empty! What to pop...!";
}
return 0;
}

void main()
{
clrscr();
stack s;
int ch=1,num;
while(ch!=0)
{
cout<<"Stack Operations Maim Men\n 1.Push\n 2.Pop\n 3.IsEmpty \n 4.IsFull \n
0.Exit";

cin>>ch;
switch(ch)
{
case 0:
exit(1); //Normal Termination of Program
case 1:
cout<<"Enter the number to push";
cin>>num;
s.push(num);
break;
case 2:
cout<<"Number popped from the stack is: "<<s.pop()<<endl;
break;
case 3:
(s.isempty())?(cout<<"Stack is empty."):(cout<<"Stack is not empty.");
break;
case 4:

19
(s.isfull())?(cout<<"Stack is full."):(cout<<"Stack is not full.");
break;
default:
cout<<"Illegal Option.Please try again";
}
}//end of while
getch();}

Output:-

Stack Operations Main Menu


1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit
1
Enter the number to push4
Stack Operations Main Menu
1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit2
Number popped from the stack is: 4
Stack Operations Main Menu
1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit4
Stack is not full.Stack Operations Main Menu
1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit3
Stack is empty.Stack Operations Main Menu
1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit

20
7)Write a program to calculate the first and follow of the given grammer.

Solution:-

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
char **arr;
int *flagstate;
int **markarr;
char **foundfirst;
int *firstisnull;
int *NtSymbols;
char **foundfollow;
int **followgoesto;

int strmergeunique(char*dest,const char *source)


{
int strlength=strlen(source),change=0;
for(int i=0;i<strlength;i++)
{
if(!strchr(dest,source[i]))
{
dest[strlen(dest)+1]='\0';
dest[strlen(dest)]=source[i];
change=1;
}
}
return change;
}
char* first(char* ch,int &k,int rowno)
{
char prod[50]={'\0'},prod1[50]={'\0'};
int i=0,isnull,preisnull=0;
while(1)
{ isnull=0;
if(isupper(ch[i]))
{int j=0;
j=NtSymbols[toascii(ch[i])-65]+1;
if(!flagstate[j-1])
{

21
strcpy(prod1,first(arr[j-1]+1,isnull,j-1));
strcpy(foundfirst[j-1],prod1);
flagstate[j-1]=1;
firstisnull[j-1]=isnull;
}
else
{
strcpy(prod1,foundfirst[j-1]);
isnull=firstisnull[j-1];}
preisnull=isnull;
// printf("first (%c)-> %s%c",arr[j-1][0],prod1,isnull?'@':' ');
strmergeunique(prod,prod1);
if(isnull==1)
{ i++;
continue;
}
else
k=k|isnull;//if k=1 k remains 1 else it is isnull
}
else
{if(ch[i]=='@')
{ k=1;}
else
{
if(ch[i]=='/')
{
i++;
k=k|preisnull;
continue;
}
if(ch[i]=='\x0'&&preisnull==1)
{
k=1;
return prod;
}
prod[strlen(prod)+1]='\0';
prod[strlen(prod)]=ch[i];}}
int prev=1;
for(int p=0;p<10&&markarr[rowno][p]!=-1;p++)
{
if(markarr[rowno][p]>i)
{
i=markarr[rowno][p]+1;

22
prev=0;
break;}}
if(!prev) continue;

return prod;
}
}
char *first(char*ch ,int &k)
{
char prod[50]={'\0'},prod1[50]={'\0'};
int i=0,isnull,preisnull=0;
if(ch[0]=='\x0')
{
k=1;
return ch;}
while(1)
{ isnull=0;
if(isupper(ch[i]))
{
int j=0;
j=NtSymbols[toascii(ch[i])-65]+1;
if(!flagstate[j-1])
{
strcpy(prod1,first(arr[j-1]+1,isnull,j-1));
strcpy(foundfirst[j-1],prod1);
flagstate[j-1]=1;
firstisnull[j-1]=isnull;}
else
{
strcpy(prod1,foundfirst[j-1]);
isnull=firstisnull[j-1];}
preisnull=isnull;
// printf("first (%c)-> %s%c",arr[j-1][0],prod1,isnull?'@':' ');
strmergeunique(prod,prod1);
if(isnull==1)
{ i++;
continue;}}
else
{
if(ch[i]=='@')
{ k=1;
}

23
else
{
if(ch[i]=='\x0'&&preisnull==1)
{
k=1;
return prod;
}
prod[strlen(prod)+1]='\0';
prod[strlen(prod)]=ch[i];
}
}
return prod;
}

}
void follow(int );
void main()
{
int nt;
clrscr();
printf("Enter no.of nonterminals :");
scanf("%d",&nt);
arr=new char*[nt];
markarr=new int*[nt];
foundfirst=new char*[nt];
foundfollow=new char*[nt];
flagstate=new int[nt];
firstisnull=new int[nt];
followgoesto=new int*[nt];
NtSymbols=new int[26];
for (int i=0;i<nt;i++)
{
arr[i]=new char[100];
markarr[i]=new int[10];
foundfirst[i]=new char[10];
memset(foundfirst[i],'\0',10);
foundfollow[i]=new char[10];
memset(foundfollow[i],'\0',10);
flagstate[i]=0;
firstisnull[i]=0;
followgoesto[i]=new int[nt];
followgoesto[i][0]=0;
printf("Enter non terminal ");

24
cin>>arr[i][0];
flushall();
printf("Enter Production for %c------>",arr[i][0]);
gets(arr[i]+1);

NtSymbols[toascii(arr[i][0])-65]=i;
for(int temp=1,k=0;temp<strlen(arr[i]);temp++)
{
if(arr[i][temp]=='/')
markarr[i][k++]=temp-1;
}
markarr[i][k]=-1;
}

char prod[50];
int isnull=0;
follow(nt);
cout<<endl<<endl;
for(i=0;i<nt;i++)
{
isnull=0;
strcpy(prod,first(arr[i]+1,isnull,i));
printf("First (%c)--> { %s %c}\n",arr[i][0],prod,isnull?'@':' ');
printf("Follow (%c)--> { %s }\n",arr[i][0],foundfollow[i]);
delete arr[i];
delete markarr[i];
delete foundfirst[i];
delete followgoesto[i];
}
delete arr;
delete markarr;
delete flagstate;
delete foundfirst;
delete firstisnull;
delete NtSymbols;
delete foundfollow;
}

void follow(int no_of_nonteminals)


{
char Beta[10]={'\0'},prod[20],BigB;
int nonterminal=0,isnull=0;
strcpy(foundfollow[0],"$");

25
while(nonterminal<no_of_nonteminals)
{

for(int eachletter=1;arr[nonterminal][eachletter]!='\0';eachletter++)
{
BigB=arr[nonterminal][eachletter];
if(isupper(BigB))
{
for(int i=eachletter+1;arr[nonterminal][i]!='/'
&&arr[nonterminal][i]!='\x0';i++)
{
Beta[i-eachletter-1]=arr[nonterminal][i];
}
Beta[i-eachletter-1]='\0';
isnull=0;
strcpy(prod,first(Beta,isnull));
strmergeunique(foundfollow[NtSymbols[toascii(BigB)-65]],prod);
if(isnull)
{
followgoesto[ nonterminal ][ followgoesto[nonterminal][0]+1
]=NtSymbols[toascii(BigB)-65];
followgoesto[nonterminal][0]++;
}
}
}
nonterminal++;
}
int change=0;
do
{
change=0;
for(int i=0;i<nonterminal;i++)
{
for(int j=1;j<=followgoesto[i][0];j++)
{
change|=strmergeunique(foundfollow[followgoesto[i][j]],foundfollow[i]);
}}}
while(change);
getch();
}

26
Output:-

Enter no.of nonterminals :3


Enter non terminal E
Enter Production for E------>B+d
Enter non terminal B
Enter Production for B------>cC
Enter non terminal C
Enter Production for C------>a+e

First (E)--> { c }
Follow (E)--> { $ }
First (B)--> { c }
Follow (B)--> { + }
First (C)--> { a }
Follow (C)--> { + }

27
8) write a program to simulate Heap allocation strategy.

Solution:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0

typedef struct Heap


{
int data;
struct Heap *next;
}
node;
node *create();
void main()
{
int choice,val;
char ans;
node*head;
void display(node*);
node *search(node*,int);
node *insert(node*);
void dele(node * *);
head = NULL;
do
{
clrscr();
printf(“\nProgram to perform various operations on Heap using Dynamic memory
management”);
printf(“\n1.Create”);
printf(“\n2.Display”);
printf(“\n3.Insert an element in a list”);
printf(“\n4.Delete an element from list”);
printf(“\n5.Quit”);
printf(“\nEnter Your Choice (1-5)”);
scanf(%d”,&choice);
switch(choice)
{
case 1:head = create();
Break;

28
case 2: display(head);
Break;
case 3: head = insert(head);
Break;
case 4: dele(&head(;
Break;
case 5: exit(0)
default:clrscr();
printf(“Invalid Choice,Try again”);
getch();
}
}
while(choice !=5);
}
node* create()
{
node *temp,*New,*head;
int val,flag;
char ans=’y’;
node *get_node();
temp = NULL;
flag = TRUE;
do
{
printf(“\n Enter the Element:”);
scanf(“%d”,&val);
New= get_node();
if (New = = NULL)
printf(“\n Memory is not allocated”);
New -> data = val;
if (flag = = TRUE)
{
head = New;
temp = head;
flag = False;
}
else
{
temp ->next = New;
temp = New;
}
printf(“\n Do you enter more elements? (y/n)”);
ans=getche();

29
}
while(ans= = ‘y’);
printf(“\n The list is created \n”);
getch();
clrscr();
return head;
}
node *get_node()
{
node *temp;
temp=(node *) malloc(sizeof(node));
temp ->next = NULL;
return temp;
}
void display(node *head)
{
node *temp;
temp=head;
if(temp==NULL)
{
printf("\nThe list is empty\n");
getch();
clrscr();
return;
}
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL");
getch();
clrscr();
}
node *search(node *head, int key)
{
node *temp;
int found;
temp=head;
if(temp==NULL)
{
printf(“The Linked List is empty\n”);
getch();

30
clrscr();
return NULL;
}
found=FALSE;
while(temp!=NULL&&found==FALSE)
{
if(temp->data!=key)
temp=temp->next;
else
found=TRUE;
}
if(found==TRUE)
{
printf(“\nThe Element is present in the list\n”);
getch();
return temp;
}
else
{
printf(“The Element is not present in the list\n”);
getch();
return NULL;
}
}
node *insert(node *head)
{
int choice;
node *insert_head(node *);
void insert_after(node *);
void insert_last(node *);
printf(“\n1.Insert a node as a head node”);
printf(“\n2.Insert a node as a last node”);
printf(“\n3.Insert a node at intermediate position in the list”);
printf(“\n Enter the your choice for insertion of node”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:head=insert_head(head);
break;
case2:insert_last(head);
break;
case 3:insert_after(head);
break;

31
}
return head;
}
node*insert_head(node*head)
{
niode*New,*temp;
New get_node();
printf("\n Enter the elemaent which you want to insert*”);
scanf(“%d”,& New->data);
if(head= =NULL)
head =New;
else
{
temp=head;
New->next=temp;
head=new;
}
return head;
}
Void insert_last(node*head)
{
node*new,*temp;
New=get_node();
printf(“\n Enter the element which you want to insert”);
scanf(%d”,& New->data);
if(head = =NULL)
head= New;
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=New;
New->next=NULL;
}
}
void insert_after(node*head)
{
int key;
node*New,*temp;
New= get_node();
print(“\n Enter the element which you want to insert
scanf(“%d”,&New->data);

32
if(head= =NULL)
{
head=New;
}
printf(“\n Enter the element after which you want to insert the node”);
scanf(“%d”,&key);
temp=head;
do
{
if(temp->data= =key)
{
New->next=temp->next;
temp->next=New;
return;
}
else
temp=temp->next;
}
while((temp!=NULL);
}
}
node *get_prev(node*head,int vall)
{
node * temp, *prev;
int flag;
temp = head;
if (temp = = NULL)
return NULL;
flag = FALSE;
prev = NULL;
while (temp!=NULL &&!flag)
{
if (temp->data! = val)
{
prev =temp;
temp= temp->next;
}
else
flag =TRUE;
}
if (flag)
return prev;
else

33
return NULL;
}
Void dele(node**head)
{
node*temp,*prev;
int key ;
temp=*head;
if(temp= = NULL)
{
printf(“\n The list is empty\n”);
getchch();
clrscr();
return;
}
clrscr();
printf(“\enter the element you want to delete:”);
Scanf(“%d”,& key);
temp= search(*head,key);
if(temp !=NULL)
{
prev= get_prev(*head,key);
if(prev!=NULL)
{
prev ->next =temp->next;
free(temp);
}
else
{
*head =temp->next;
free(temp);// using the mem. de-allocation function
}
printf(“\the element is deleted\n”);
getch();
clrscr();
}
}

Output:-

program to perform various operation on heap using dynamic memory management


1.create
2.display
3.insert an element in list

34
4.delete an element from list
5.quit
Enter your Choice(1-5)1

Enter the Element :10

Do you want to enter more elements?(y/n)y


Enter the Element:20

Do you want to enter more elements?(y/n)y


Enter the Element:30

Do you want to enter more elements?(y/n)

The list is created

Program to perform various operation on heap using dynamic memory management


1. create
2.display
3. insert an element in list
4.delete an element from list
5.quit
Enter your choice(1-5)2
10-> 20-> 30-> null

Program to perform various operation on heap using dynamic memory management


1. Create
2.Display
3. Insert an element in list
4.Delete an element from list
5.Quit
Enter the element you want to delete:20

The Element is present in list

The Element is deleted

Program to perform various operation on heap using dynamic memory management


1.Create
2.Display
3.Insert an element in list

35
4.Delete an element from list
5.Quit
Enter Your Choice(1-5)2
10-> 30-> NULL

36
9) Given any intermediate code form implement code optimization techniques.

Solution:-

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

Struct ConstFold
{
char New_Str[10];
char str[10];
}Opt_Data[20];

Void ReadInput(char Buffer[],FILE *Out_file);


int Gen_Token(char str[],char Tokens[][10]);

int New_index=0;

int main()
{
FILE *in_file,*Out_file;
char Buffer[100],ch;
int i=0;
in_file =fopen(“d:\\code.txt”,”r”);
out_file =fopen(“d:\\output.txt”,”w”);
clrscr();
while(1);
{
ch =fgetc(In_file);
i=0;
while(1)
{
if(ch = = ‘\n’)
break;
Buffer[i++] = ch;
ch =fgetc(In_file);
if(ch = =EOF)
break;
}
if(ch= =EOF)

37
break;
buffer[i]=’\0’;
ReadInput(Buffer,Out_file);
}
return 0;
}

void ReadInput(char Buffer[],FILE *Out_file)


{
char temp[100],Token[10][10];
int n,I,j,flag=0;
strcpy(temp,buffer);
n =Gen_Token(temp,Token);
for(i=0;i<n;i++)
{
if(!strcmp(Token[i],”=”))
{
if(isdigit(Token[i+1][0]) ║Token[i+1][0] = = ‘.’
{
flag =1;
strcpy(Opt_Data[New_index].New_Str,Token[i-1]
strcpy(Opt_Data[New_index++].Str,Token[i+1]);
}
}
}
if(!flag)
{
for(i=0;j<New_index;;i++)
{
for(j=0;j<n;j++)
{
if(!strcmp(Opt_Data[i].New_Str,Token[j]))
strcpy(Token[j],Opt_Data[i].str);
}
}
}
fflush(out_file);
strcpy(temp,””);
for(i=0;i<n;i++)
{
strcat(temp,Token[i]);
if(token[i+1][0]!=’.’║Token[i+1][0]!=’;’)
strcat(temp,” ”);

38
}
strcat(temp,”\n\0”);

fwrite(&temp,strlen(temp),1,Out_file);
}

int Gen_token(char str[],char Token[][10])


{
int i=0,j=0,k=0;
while(str[k]= =’’॥ str[k]= =’\t’)
k++;
while(str[k]!=’\0’)
{
j=0;
while(str[k])= =’’ ॥ str[k]= =’\t’)
k++
while(str[k]!=’’&& str[k]!=’\0’
&& str[k]!=’=’ && str[k]!=’/’
&& str[k]!=’+’ && str[k]!=’-’
&& str[k]!=’*’ && str[k]!=’,’ &&str[k]!=’;’)
Token[i][j++] = str[k++] ;
Token [i++][j]= ‘\0’;
if(str[k]= =’=’ ॥ str[k]= =’/’ ॥ str[k]= =’+’ ॥ str[k]= =’-’ ॥ str[k]= =’*’ ॥ str[k]= =’,’ ॥ str[k]=
=’;’ )
{
Token[i][0]=str[k++];
Token[i++][1]=’\0’;
}
if(str[k]= =’\0’)
break;
}
return i;
}

Input file: code.txt

#include<stdio.h>
main()
{
float pi=3.14,r,a;
a=pi*r*r;
printf(“a = %f”,a);

39
return 0;
}

Output File: output.txt

#include<stdio.h>
main()
{
float pi=3.14,r,a;
a=3.14*r*r;
printf(“a = %f”,a);
return 0;
}

40
10) Write a lex program to convert the substring abc to ABC from the given
input string.

Solution:-

%{
#include<stdio.h>
#include<string.h>
int i;
%}
%%
[a-zA-Z]* {
for(i=0;i<yyleng;i++)
{
if((yytext[i]==’a’)&&(yytext[i+1]==’b’)&&(yytext[i+2]==’c’))
{
yytext[i]=’A’;
yytext[i+1]=’B’
yytext[i+2]=’C’
}
}
printf(“%s”’yytext);
}
[\t]* return;
.* {ECHO;}
\n {printf(“%s”,yytext);}
%%
main()
{
yylex();
}
int yywrap()
{
return 1;
}
Output:-

[root@aap Syssoftprograms]# vi abctest.l


[root@aap Syssoftprograms]# lex abctest.l
[root@aap Syssoftprograms]# cc lex.yy.c
[root@aap Syssoftprograms]# ./a.out
helloabcabcworld
helloABCABCworld

41
11) Write a lex program to find out total number of vowels and consonants
from the given input string.

Solution:-

%{
/*Definition section*/
int vowel_cnt=0,consonant_cnt=0;
%}
vowel [aeiou]+
consonant [^aeiou]
eol \n
%%
{eol} return 0;
[ \t]+ ;
{vowel} {vowel_cnt++;}
{consonant} {consonant_cnt++;}
%%
int main()
{
printf(“\n Enter some input string\n);
yylex();
printf(“Vowels=%d and consonant=%d\n”,vowel_cnt,consonant_cnt);
return 0;
}
int yywrap()
{
return 1;
}

Output:-

[root@aap root]# lex vowel.l


[root@aap root]# cc lex.yy.c
[root@aap root]# ./a.out
Enter some input string
parth
Vowels=1 and consonant=4
[root@aap root]#

42
12)Write a lex program to identify the capital strings from the given input
string.

Solution:-

/*Definition section*/
%}
%%
[A-Z]+[ \t\n\.\,] {printf(“%s”,yytext);}
. ;
%%
main()
{
printf(“\n Enter some input with capital words in between\n”);
yylex();
}
int yywrap()
{
return 1;
}

Output:-

[root@aap root]# lex upper.l


[root@aap root]# gcc lex.yy.c -ll
[root@aap root]# ./a.out

Enter some input with capital words in between


I am PROUD of you – INDIA
I PROUD INDIA

43

You might also like