SlideShare a Scribd company logo
1 of 87
Download to read offline
||Jai Sri Gurudev||
BGSKH Education Trust
BGS COLLEGE OF ENGINEERING AND
TECHNOLOGY
MAHALAKSHMIPURAM, BENGALURU - 560086
Data Structures Lab Manual
For third Semester BE [VTU/CBCS, 2022 Scheme]
Subject Code:
Name: ……………………………………………………..….
Branch: ………………………………………………….……
USN: ……………………………….……………………….…
B C S L 3 0 5
i
PREFACE
C programming language offers several facilities to group data together in
convenient packages, or data structures. With the emergence of C as the most
popular language of implementation blossomed from Bell laboratories.
This book for practical “Data Structures laboratory” is an introduction to all
popular data structures and their implementation with the C language. It is
planned for beginners who would like to learn the subject through programs.
This edition emphasizes on abstract concepts of Data Structures and describes
how these are useful in problem solving using structures such as queues, arrays,
linked lists, stacks, trees and graphs. Students will gain a good appreciation of the
subject as this book has a clear display of syntax and elegant programming
examples. To simplify concepts, the data structures are implemented using C
language, in a step-by-step manner.
BGS College of Engineering & Technology
Department of Computer Science and Engineering
Vision
Nurturing young minds to making them industry ready IT professionals
Mission
M1: Providing strong foundational knowledge of mathematics, science, and computational
approaches on solving theoretical and practical problems of Computer Science.
M2: Imparting high quality advanced knowledge in experiential learning to get expertise in
modern software tools and to cater to the real time requirements of the industry.
M3: Fostering the professionalism to achieve goals by inculcating niche skills for Successful
Entrepreneur
M4: Provide a conducive environment to train students in progressive and convergent
research themes.
M5: Inculcate problem solving and team building skills and promote lifelong learning with
a sense of societal and value based ethical responsibilities
PROGRAM EDUCATIONAL OBJECTIVES
PEO1: Graduates will be able to demonstrate technical competency and leadership by
accomplishing Engineering knowledge, mathematics, science & engineering fundamentals.
ii
PEO2: Graduates will be able to analyse and understand current pedagogical techniques,
industry accepted computing practices and state-of-art technology to deliver solutions by
creative intuitions towards technological growth and societal needs.
PEO3: Graduates will be able to exhibit cultural awareness, teamwork with professional
ethics, effective communication skills and leader qualities to achieve higher career goals.
PEO4: Graduates will be able to pursue higher education in pursuit of lifelong learning and
explore the research possibilities, entrepreneurship opportunities and novel innovation
practices.
PROGRAM SPECIFIC OUTCOMES
PSO1: Demonstrate the use of knowledge and ability to develop applications and integrate
them in the areas related to Databases, Web programming, Artificial Intelligence and
machine learning, Data Science, and allied areas.
PSO2: Identify the various analysis & design methodologies for facilitating development of
effective algorithms and code for high quality system software products with focus on
performance optimization.
PSO3: Develop the capability of comprehending the technological advancements in the
practice of modern design tools in planning and implementing solutions to cater to business
– specific requirements exhibiting team dynamics and professional ethics.
iii
PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the
solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and
analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the professional engineering
practice.
7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
iv
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as
a member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.
11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest
context of technological change.
v
INDEX
Sl.No Contents Page No
1 Lab assessment rubrics for CIE ix
2 Develop a Program in C for the following: a) Declare a
calendar as an array of 7 elements (A dynamically Created
array) to represent 7 days of a week. Each Element of the array
is a structure having three fields. The first field is the name of
the Day (A dynamically allocated String), The second field is
the date of the Day (A integer), the third field is the description
of the activity for a particular day (A dynamically allocated
String).
b) Write functions create(), read() and display(); to create the
calendar, to read the data from the keyboard and to print weeks
activity details report on screen.
1
3 Develop a Program in C for the following operations on
Strings.
a. Read a main String (STR), a Pattern String (PAT) and a
Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all
occurrences of PAT in STR with REP if PAT exists in STR.
Report suitable messages in case PAT does not exist in STR
Support the program with functions for each of the above
operations. Don't use Built-in functions.
4
4 Develop a menu driven Program in C for the following
operations on STACK of Integers (Array Implementation of
Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit Support the program with appropriate functions for each
of the above operations
6
5 Develop a Program in C for converting an Infix Expression to
Postfix Expression. Program should support for both
parenthesized and free parenthesized expressions with the
operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric
operands.
16
6 Develop a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands
and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks
19
7 Develop a menu driven Program in C for the following
operations on Circular QUEUE of Characters (Array
23
vi
Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular
QUEUE
d. Display the status of Circular QUEUE
e. Exit Support the program with appropriate functions for each
of the above operations
8 Develop a menu driven Program in C for the following
operations on Singly Linked List (SLL) of Student Data with
the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in
it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration
of stack)
e. Exit
28
9 Develop a menu driven Program in C for the following
operations on Doubly Linked List (DLL) of Employee Data
with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in
it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended
Queue.
f. Exit
38
10 Develop a Program in C for the following operationson Singly
Circular Linked List (SCLL) with header nodes a. Represent
and Evaluate
a Polynomial P(x,y,z) = 6x2
y2
z-4yz5
+3x2
yz+2xy5
z-2xyz3
b. Find the sum of two polynomials POLY1(x,y,z) and
POLY2(x,y,z) and store the result in POLYSUM(x,y,z)
Support the program with appropriate functions for each of the
above operations
49
11 Develop a menu driven Program in C for the following
operations on Binary Search Tree (BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the
appropriate message
d. Exit
58
vii
12 Develop a Program in C for the following operations on
Graph(G) of Cities a. Create a Graph of N cities using
Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a
digraph using DFS/BFS method
66
13 Given a File of N employee records with a set K of Keys (4-
digit) which uniquely determine the records in file F. Assume
that file F is maintained in memory by a Hash Table (HT) of m
memory locations with L as the set of memory addresses (2-
digit) of locations in HT. Let the keys in K and addresses in L
are Integers. Develop a Program in C that uses Hash function
H: K →L as H(K)=K mod m (remainder method), and
implement hashing technique to map a given key K to the
address space L. Resolve the collision (if any) using linear
probing.
70
14 Appendix A 72
15 Appendix B 75
Laboratory Outcomes:
The student should be able to:
● Analyze various linear and non-linear data structures.
● Demonstrate the working nature of different types of data structures and their
applications
● Use appropriate searching and sorting algorithms for the given scenario.
● Apply the appropriate data structure for solving real world problems.
Conduct of Practical Examination:
● Experiment distribution
○ For laboratories having only one part: Students are allowed to pick one
experiment from the lot with equal opportunity.
○ For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal
opportunity.
● Change of experiment is allowed only once and marks allotted for procedure to be made
zero of the changed part only.
● Marks Distribution (Need to change in accordance with university regulations)
○ For laboratories having only one part – Procedure + Execution + Viva-Voce:
15+70+15 = 100 Marks
viii
○ For laboratories having PART A and PART B
■ Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
■ Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
Course objectives:
CO1 Analyze various linear and non-linear data structures
CO2 Demonstrate the working nature of different types of data structures and
their applications
CO3 Use appropriate searching and sorting algorithms for the give scenario.
CO4 Apply the appropriate data structure for solving real world problems
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO1
1
PO12
CO1 3 - 3 - - - - - - - - -
CO2 2 2 3 - - - - - - - - -
CO3 2 2 3 - - - - - - - - -
CO4 - - - - - - - - 2 2 - -
ix
Lab Assessment Rubrics for CIE
Sl No Description Marks
1 Continuous Evaluation 30
a. Observation write up and punctuality 5
b. Conduction of experiment and output 10
c. Viva voice 5
d. Record write up 10
2 Internal Test 20
1
Department of CS&E, BGSCET
Program 1:
Develop a Program in C for the following:
a) Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days
of a week. Each Element of the array is a structure having three fields. The first field is the name
of the Day (A dynamically allocated String), The second field is the date of the Day (A integer), the
third field is the description of the activity for a particular day (A dynamically allocated String).
b) Write functions create(), read() and display(); to create the calendar, to read the data from the
keyboard and to print weeks activity details report on screen.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define the structure for each day of the week
struct Day {
char *name;
int date;
char *activity;
};
// Define an array to store 7 days of the week
struct Day week[7];
// Function to create the calendar
void create() {
for (int i = 0; i < 7; i++) {
week[i].name = (char *)malloc(20 * sizeof(char));
week[i].activity = (char *)malloc(100 * sizeof(char));
printf("Enter the name of day %d: ", i + 1);
scanf("%s", week[i].name);
printf("Enter the date of day %d: ", i + 1);
scanf("%d", &week[i].date);
printf("Enter the activity for day %d: ", i + 1);
getchar(); // Consume the newline character
fgets(week[i].activity, 100, stdin);
}
}
// Function to read data from the keyboard
void read() {
create(); // Reusing the create function for reading data
2
Department of CS&E, BGSCET
}
// Function to display the calendar
void display() {
printf("nDaytDatetActivityn");
for (int i = 0; i < 7; i++) {
printf("%st%dt%s", week[i].name, week[i].date, week[i].activity);
}
}
int main() {
printf("Creating a calendar:n");
create();
printf("nDisplaying the calendar:n");
display();
return 0;
}
Output:
Creating a calendar:
Enter the name of day 1: Monday
Enter the date of day 1: 30
Enter the activity for day 1: 3rd Sem starts
Enter the name of day 2: Tuesday
Enter the date of day 2: 31
Enter the activity for day 2: Interaction with juniors
Enter the name of day 3: Wednesday
Enter the date of day 3: 1
Enter the activity for day 3: Kannada Rajyotsava
Enter the name of day 4: Thursday
Enter the date of day 4: 2
Enter the activity for day 4: Technical Talk from Industry Experts
Enter the name of day 5: Friday
Enter the date of day 5: 3
Enter the activity for day 5: Cultural Activities
Enter the name of day 6: Saturday
3
Department of CS&E, BGSCET
Enter the date of day 6: 4
Enter the activity for day 6: Hands on session (Web Designing)
Enter the name of day 7: Saturday
Enter the date of day 7: 5
Enter the activity for day 7: Refreshment
Displaying the calendar:
Day Date Activity
Monday 30 3rd Sem starts
Tuesday 31 Interaction with juniors
Wednesday 1 Kannada Rajyotsava
Thursday 2 Technical Talk from Industry Experts
Friday 3 Cultural Activities
Saturday 4 Hands on session (Web Designing)
Sunday 5 Refreshment
4
Department of CS&E, BGSCET
Program 2
Develop a Program in C for the following operations on Strings. a. Read a main String (STR), a
Pattern String (PAT) and a Replace String (REP) b. Perform Pattern Matching Operation: Find
and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable
messages in case PAT does not exist in STR Support the program with functions for each of the
above operations. Don't use Built-in functions.
#include<stdio.h>
char str[50], pat[20], rep[20], ans[50];
int c=0, m=0, i=0, j=0, k, flag=0;
void stringmatch()
{
while(str[c] !='0')
{
if(str[m] == pat[i])
{
i++;
m++;
if(pat[i] == '0')
{
flag = 1;
for(k=0; rep[k]!='0'; k++, j++)
{
ans[j] = rep[k];
}
i = 0;
c = m;
}
}
else
{
ans[j]= str[c];
j++;
c++;
5
Department of CS&E, BGSCET
m=c;
i=0;
}
}
ans[j]='0';
}
void main()
{
printf("nEnter the main string:");
gets(str);
printf("nEnter the pat string:");
gets(pat);
printf("nEnter the replace string:");
gets(rep);
stringmatch();
if(flag == 1)
printf("nResultant string is %s", ans);
else
printf("nPattern string is not found");
}
Output:
Enter the main string: Welcome to BGSgroups
Enter the pat string: groups
Enter the replace string: CET
Resultant string is Welcome to BGSCET
6
Department of CS&E, BGSCET
Program 3:
Develop a menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack f. Exit Support the program with appropriate functions for each
of the above operations.
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
int s[MAX];
int top = -1;
void push(int item);
int pop();
void palindrome();
void display();
void main()
{
int choice, item;
while(1)
{
printf("nnnn~~~~~~Menu~~~~~~ : ");
printf("n=>1.Push an Element to Stack and Overflow demo ");
printf("n=>2.Pop an Element from Stack and Underflow demo");
printf("n=>3.Palindrome demo ");
printf("n=>4.Display ");
printf("n=>5.Exit");
printf("nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
7
Department of CS&E, BGSCET
case 1: printf("nEnter an element to be pushed: ");
scanf("%d", &item);
push(item);
break;
case 2: item = pop();
if(item != -1)
printf("nElement popped is: %d", item);
break;
case 3: palindrome();
break;
case 4: display();
break;
case 5: exit(1);
default: printf("nPlease enter valid choice ") ;
break;
}
}
}
void push(int item)
{
if(top == MAX-1)
{
printf("n~~~~Stack overflow~~~~");
return;
}
top = top + 1 ;
s[top] = item;
}
int pop()
{
int item;
8
Department of CS&E, BGSCET
if(top == -1)
{
printf("n~~~~Stack underflow~~~~");
return -1;
}
item = s[top];
top = top - 1;
return item;
}
void display()
{
int i;
if(top == -1)
{
printf("n~~~~Stack is empty~~~~");
return;
}
printf("nStack elements are:n ");
for(i=top; i>=0 ; i--)
printf("| %d |n", s[i]);
}
void palindrome()
{
int flag=1,i;
printf("nStack content are:n");
for(i=top; i>=0 ; i--)
printf("| %d |n", s[i]);
printf("nReverse of stack content are:n");
for(i=0; i<=top; i++)
printf("| %d |n", s[i]);
9
Department of CS&E, BGSCET
for(i=0; i<=top/2; i++)
{
if( s[i] != s[top-i] )
{
flag = 0;
break;
}
}
if(flag == 1)
{
printf("nIt is palindrome number");
}
else
{
printf("nIt is not a palindrome number");
}
}
Output:
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 25
10
Department of CS&E, BGSCET
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 26
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 27
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 28
11
Department of CS&E, BGSCET
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 28 |
| 27 |
| 26 |
| 25 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 28
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
12
Department of CS&E, BGSCET
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 27 |
| 26 |
| 25 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
Stack content are:
| 27 |
| 26 |
| 25 |
Reverse of stack content are:
| 25 |
| 26 |
| 27 |
It is not a palindrome number
13
Department of CS&E, BGSCET
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 5
Output 2:
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 1
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 2
~~~~~~Menu~~~~~~ :
14
Department of CS&E, BGSCET
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 1
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 1 |
| 2 |
| 1 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 3
15
Department of CS&E, BGSCET
Stack content are:
| 1 |
| 2 |
| 1 |
Reverse of stack content are:
| 1 |
| 2 |
| 1 |
It is palindrome number
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 5
16
Department of CS&E, BGSCET
Program 4:
Develop a Program in C for converting an Infix Expression to Postfix Expression. Program
should support for both parenthesized and free parenthesized expressions with the operators: +, -,
*, /, % (Remainder), ^ (Power) and alphanumeric operands.
#include <ctype.h>
#include <stdio.h>
#define SIZE 50 /* Size of Stack */
char s[SIZE]; /* Global declarations */
int top = -1;
push(char elem) /* Function for PUSH operation */
{
s[++top] = elem;
}
char pop() /* Function for POP operation */
{
return (s[top--]);
}
int pr(char elem) /* Function for precedence */
{
switch (elem)
{
case '#': return 0; case '(': return 1; case '+':
case '-': return 2; case '*':
case '/':
case '%': return 3; case '^':
return 4;
}
}
void main() /* Main Program */
{
17
Department of CS&E, BGSCET
char infx[50], pofx[50], ch, elem; int i = 0, k = 0;
printf("nn enter the Infix Expression : ");
gets(infx);
push('#');
while ((ch = infx[i++]) != '0')
{
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')')
{
while (s[top] != '(') pofx[k++] = pop();
elem = pop(); /* Remove ( */
}
else /* Operator */
{
while (pr(s[top]) >= pr(ch)) pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '0'; /* Make pofx as valid string */
printf("nn Given Infix Expn is: %sn The Postfix Expn is:%sn", infx, pofx);
}
Output 1:
enter the Infix Expression : a+b-c*d
Given Infix Expn is: a+b-c*d
The Postfix Expn is: ab+cd*-
18
Department of CS&E, BGSCET
Output 2:
enter the Infix Expression : a+(b-c)*d/e^f
Given Infix Expn is: a+(b-c)*d/e^f
The Postfix Expn is:abc-d*ef^
19
Department of CS&E, BGSCET
Program 5:
Develop a Program in C for the following Stack Applications a. Evaluation of Suffix expression
with single digit operands and operators: +, -, *, /, %, ^
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int i, top = -1;
int op1, op2, res, s[20];
char postfix[90], symb;
void push(int item)
{
top = top+1;
s[top] = item;
}
int pop()
{
int item;
item = s[top];
top = top-1;
return item;
}
void main()
{
printf("nEnter a valid postfix expression:n");
scanf("%s", postfix);
for(i=0; postfix[i]!='0'; i++)
{
symb = postfix[i];
if(isdigit(symb))
20
Department of CS&E, BGSCET
{
push(symb - '0');
}
else
{
op2 = pop();
op1 = pop();
switch(symb)
{
case '+': push(op1+op2);
break;
case '-': push(op1-op2);
break;
case '*': push(op1*op2);
break;
case '/': push(op1/op2);
break;
case '%': push(op1%op2);
break;
case '$':
case '^': push(pow(op1, op2));
break;
default : push(0);
}
}
}
res = pop();
printf("n Result = %d", res);
}
Output:
Enter a valid postfix expression:
651-4*23$/+
21
Department of CS&E, BGSCET
Result = 8
Output 2:
Enter a valid postfix expression:
861-*2/32^%
Result = 2
b. Solving Tower of Hanoi problem with n disks
#include<stdio.h>
#include<conio.h> int count=0,n;
int tower(int n,char s,char t,char d)
{
if(n==1)
{
printf("n Move disc 1 from %c to %c",s,d); count++;
return 1;
}
tower(n-1,s,d,t);
printf("n Move disc %d from %c to %c",n,s,d); count++;
tower(n-1,t,s,d);
}
int main( )
{
printf("n Enter the no. of discs:");
scanf("%d",&n);
tower(n,'A','B','C');
printf("n The no. of disc moves is:%d",count);
getch( );
}
22
Department of CS&E, BGSCET
Output 1:
Enter the no. of discs:2
Move disc 1 from A to B
Move disc 2 from A to C
Move disc 1 from B to C
The no. of disc moves is:3
Output 2:
Enter the no. of discs:4
Move disc 1 from A to B
Move disc 2 from A to C
Move disc 1 from B to C
Move disc 3 from A to B
Move disc 1 from C to A
Move disc 2 from C to B
Move disc 1 from A to B
Move disc 4 from A to C
Move disc 1 from B to C
Move disc 2 from B to A
Move disc 1 from C to A
Move disc 3 from B to C
Move disc 1 from A to B
Move disc 2 from A to C
Move disc 1 from B to C
The no. of disc moves is: 15
23
Department of CS&E, BGSCET
Program 6:
Develop a menu driven Program in C for the following operations on Circular QUEUE of
Characters (Array Implementation of Queue with maximum size MAX) a. Insert an Element onto
Circular QUEUE b. Delete an Element from Circular QUEUE c. Demonstrate Overflow and
Underflow situations on Circular QUEUE d. Display the status of Circular QUEUE e. Exit Support
the program with appropriate functions for each of the above operations.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 5
int q[SIZE], i, r=-1, f=0, option, count=0, j;
int main( )
{
for(;;)
{
printf("n 1.Insert 2.Deleten 3.Display 4.Exit");
printf("nEnter your option:");
scanf("%d",&option);
switch(option)
{
case 1: //Inserting items to Queue
if(count==SIZE)
printf("n Q is Fulln");
else
{
r=(r+1)%SIZE;
printf("nEnter the item:");
scanf("%d",&q[r]);
count++;
}
break;
case 2: //Deleting items from Queue
if(count==0)
24
Department of CS&E, BGSCET
printf("nQ is emptyn");
else
{
printf("nDeleted item is: %d",q[f]);
count--;
f=(f+1)%SIZE;
}
break;
case 3: //Displaying items from Queue
if(count==0)
printf("nQ is Emptyn");
else
{
i=f;
for(j=0;j<count;j++)
{
printf(" %d",q[i]);
i=(i+1)%SIZE;
}
}
break;
default: exit(0);
}
}
}
Output:
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:10
25
Department of CS&E, BGSCET
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:20
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:30
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:40
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:50
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Q is Full
26
Department of CS&E, BGSCET
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:3
10 20 30 40 50
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Deleted item is: 10
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Deleted item is: 20
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:3
30 40 50
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:1
Enter the item:60
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Deleted item is: 30
1.Insert 2.Delete
27
Department of CS&E, BGSCET
3.Display 4.Exit
Enter your option:2
Deleted item is: 40
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Deleted item is: 50
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Deleted item is: 60
1.Insert 2.Delete
3.Display 4.Exit
Enter your option:2
Q is empty
28
Department of CS&E, BGSCET
Program 7:
Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of
Student Data with the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it.
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
char usn[11];
char name[25];
int sem;
char branch[5];
unsigned long long phno;
};
typedef struct student STUD;
struct node
{
char usn[11];
char name[25];
int sem;
char branch[5];
unsigned long long phno;
struct node *next;
};
typedef struct node NODE;
NODE *first;
NODE* copyNode(STUD s)
{
NODE * temp;
29
Department of CS&E, BGSCET
temp= (NODE *)malloc(sizeof(NODE));
if(temp==NULL)
{
printf("Memory cannot be allocatedn");
}
else
{
strcpy(temp->usn,s.usn);
strcpy(temp->name, s.name);
strcpy(temp->branch, s.branch);
temp->sem=s.sem;
temp->phno=s.phno;
temp->next=NULL;
return temp;
}
}
void addrear(STUD s)
{
NODE *temp,*cur;
temp=copyNode(s) ;
if(first==NULL)
{
temp=first;
return;
}
cur=first;
while(cur->next != NULL)
{
cur=cur->next;
}
cur->next =temp;
return ;
}
void addfront(STUD s)
30
Department of CS&E, BGSCET
{
NODE *temp;
temp=copyNode(s); //ssn,name, dept, design,salary, pno);
if (first== NULL)
{
first=temp;
}
else
{
temp->next=first;
first=temp;
}
return ;
}
void display(NODE *temp)
{
printf("%s t", temp->usn);
printf("%s t", temp->name);
printf("%s t", temp->branch);
printf("%d t",temp->sem);
printf("%llu n", temp->phno);
}
void deletefront()
{
NODE *temp;
int num;
temp=first;
if(first==NULL)
{
printf("List is Empty");
return;
}
if(first->next==NULL)
31
Department of CS&E, BGSCET
first=NULL;
else
{
first=first->next;
}
printf("Deleted Node is:n");
display(temp);
free(temp);
return;
}
void deleterear()
{
NODE *cur,*prev;
cur=first;
prev=NULL;
if(first==NULL)
{
printf("List is Empty");
return;
}
if(first->next==NULL)
{
display(cur);
first=NULL;
free(cur);
return;
}
while(cur->next!=NULL)
{
prev=cur;
cur=cur->next;
}
prev->next=NULL;
printf("Deleted Node is:n");
32
Department of CS&E, BGSCET
display(cur);
free(cur);
return;
}
void displayList()
{
NODE *r;
r=first;
printf("USNtNametBrhtSemtPhonen");
if(r==NULL)
return;
while(r!=NULL)
{
display(r);
r=r->next;
}
printf("n");
}
STUD input()
{
STUD s;
printf("Enter USN: ");
scanf("%s",s.usn);
printf("Enter Name : ");
scanf("%s",s.name);
printf("Enter Branch: ");
scanf("%s",s.branch);
printf("Enter Sem:");
scanf("%d",&s.sem);
printf("Enter Phone no : ");
scanf("%llu",&s.phno);
return s;
}
int count()
33
Department of CS&E, BGSCET
{
NODE *n;
int c=0;
n=first;
while(n!=NULL)
{
n=n->next;
c++;
}
return c;
}
int main()
{
STUD s;
int i,ch, n;
first=NULL;
while(1)
{
printf("nList Operationsn");
printf("===============n");
printf("1.Create List of n students by using front Insertn");
printf("2.Display the status and count the nodesn");
printf("3.Perform Insertion and Deletion at End of SLLn");
printf("4.Perform Insertion and Deletion at Front of SLLn");
printf("5.Exitn"); printf("Enter your choice : ");
scanf("%d",&i);
switch(i)
{
case 1 : printf("Enter the number of studentsn");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("nEnter the details of student %dn",i);
s=input();
34
Department of CS&E, BGSCET
addfront(s);
}
break;
case 2 : if(first==NULL)
{
printf("List is Emptyn");
}
else
printf(" Node Count=%dt & Elements in the list are : n", count());
displayList();
}
break;
case 3 : printf(" 1. Insert at End and 2 Delete From End=");
scanf("%d",&ch);
if(ch==1)
{
s=input(); addrear(s);
}
else if(ch==2)
deleterear();
else
printf(" Sorry wrong operationn"); break;
case 4 : printf(" 1. Insert at Front and 2.Delete From Front=");
scanf("%d",&ch);
if(ch==1)
{
s=input(); addfront(s);
}
else if(ch==2)
deletefront();
else
printf(" Sorry wrong operationn");
case 5 :exit (0);
default : printf("Invalid optionn");
}
}
return 0;
}
35
Department of CS&E, BGSCET
Output
List Operations
===============
1.Create List of n students by using front Insert
2.Display the status and count the nodes
3.Perform Insertion and Deletion at End of SLL
4.Perform Insertion and Deletion at Front of SLL
5.Exit
Enter your choice : 1
Enter the number of students
2
Enter the details of student 1
Enter USN: 1mp22is001
Enter Name : aishwarya
Enter Branch: ise
Enter Sem:3
Enter Phone no : 8765432192
Enter the details of student 2
Enter USN: 1mp22cs002
Enter Name : abhishek
Enter Branch: cse
Enter Sem:3
Enter Phone no : 9876543213
List Operations
===============
1.Create List of n students by using front Insert
2.Display the status and count the nodes
3.Perform Insertion and Deletion at End of SLL
4.Perform Insertion and Deletion at Front of SLL
5.Exit
Enter your choice : 3
1. Insert at End and 2 Delete From End=1
Enter USN: 1mp22ec003
Enter Name : asha
Enter Branch: ec
36
Department of CS&E, BGSCET
Enter Sem:3
Enter Phone no : 8976543218
List Operations
===============
1.Create List of n students by using front Insert
2.Display the status and count the nodes
3.Perform Insertion and Deletion at End of SLL
4.Perform Insertion and Deletion at Front of SLL
5.Exit
Enter your choice : 2
Node Count=3 & Elements in the list are :
USN Name Brh Sem Phone
1mp22cs002 abhishek cse 3 9876543213
1mp22is001 aishwarya ise 3 8765432192
1mp22ec003 asha ec 3 8976543218
List Operations
===============
1.Create List of n students by using front Insert
2.Display the status and count the nodes
3.Perform Insertion and Deletion at End of SLL
4.Perform Insertion and Deletion at Front of SLL
5.Exit
Enter your choice : 2
Node Count=3 & Elements in the list are :
USN Name Brh Sem Phone
1mp22cs002 abhishek cse 3 9876543213
1mp22is001 aishwarya ise 3 8765432192
1mp22ec003 asha ec 3 8976543218
List Operations
===============
1.Create List of n students by using front Insert
2.Display the status and count the nodes
3.Perform Insertion and Deletion at End of SLL
4.Perform Insertion and Deletion at Front of SLL
37
Department of CS&E, BGSCET
5.Exit
Enter your choice : 4
1. Insert at Front and 2.Delete From Front=2
Deleted Node is:
1mp22cs002 abhishek cse 3 9876543213
38
Department of CS&E, BGSCET
Program 8:
Develop a menu driven Program in C for the following operations on Doubly Linked List
(DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it.
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit
#include<stdio.h>
#include<stdlib.h>
#include<string.h> struct employee
{
char ssn[11];
char name[21];
char dept[15];
char design[15];
int salary;
unsigned long long phno;
};
typedef struct employee EMP; struct node
{
char ssn[11];
char name[21];
char dept[15];
char design[15];
int salary;
unsigned long long phno;
struct node *next;
struct node *prev;
};
typedef struct node NODE;
NODE *first;
NODE* copyNode(EMP e)
{
NODE * temp;
temp= (NODE *)malloc(sizeof(NODE));
if(temp==NULL)
39
Department of CS&E, BGSCET
{
printf("Memory cannot be allocatedn");
}
else
{
strcpy(temp->ssn,e.ssn);
strcpy(temp->name, e.name);
strcpy(temp->dept, e.dept);
strcpy(temp->design, e.design);
temp->salary=e.salary;
temp->phno=e.phno;
temp->next=NULL;
temp->prev=NULL;
return temp;
}
}
void addrear(EMP e)
{
NODE *temp,*cur, *prev;
temp=copyNode(e) ;
if(first==NULL)
{
first=temp;
return;
}
cur=first;
prev=NULL;
while(cur->next != NULL)
{
prev=cur;
cur=cur->next;
}
cur->next =temp;
temp->prev=prev;
return ;
}
void addfront(EMP e)
{
NODE *temp;
40
Department of CS&E, BGSCET
temp=copyNode(e);
if (first== NULL)
{
first=temp;
}
else
{
temp->next=first;
first->prev=temp;
first=temp;
}
return ;
}
void display(NODE *r)
{
printf("%st", r->ssn);
printf("%st", r->name);
printf("%st", r->dept);
printf("%st",r->design);
printf("%dt",r->salary);
printf("%llun", r->phno);
}
void deletefront()
{
NODE *temp;
int num;
temp=first;
if(first==NULL)
{
printf(" List is Empty n");
return ;
}
if(first->next==NULL)
first=NULL;
else
{
first=first->next;
first->prev=NULL;
}
41
Department of CS&E, BGSCET
printf("SSNtNametDepttDesignationtSalarytPhonen");
display(temp);
free(temp);
return ;
}
void deleterear()
{
NODE *cur, *prev;
cur=first;
prev=NULL;
if(first==NULL)
{
printf(" List is Empty n");
return ;
}
if(first->next==NULL)
{
first=NULL;
}
else
{
while(cur->next!=NULL)
{
prev=cur;
cur=cur->next;
}
prev->next=NULL;
}
printf("SSNtNametDepttDesignationtSalarytPhonen"); display(cur);
free(cur);
return;
}
void displayList()
{
NODE *r;
r=first;
if(r==NULL)
{
return;
42
Department of CS&E, BGSCET
}
printf("SSNt Namet Deptt Designationt salarytPhonen");
while(r!=NULL)
{
display(r);
r=r->next;
}
printf("n");
}
int count()
{
NODE *n;
int c=0;
n=first;
while(n!=NULL)
{
n=n->next; c++;
}
return c;
}
EMP input()
{
EMP e;
printf("Enter SSN: ");
scanf("%s",e.ssn);
printf("Enter Name: ");
scanf("%s",e.name);
printf("Enter dept: ");
scanf("%s",e.dept);
printf("Enter Designation :");
scanf("%s",e.design);
printf("Enter Salary:");
scanf("%d",&e.salary);
printf("Enter Phone no : ");
scanf("%llu",&e.phno);
return e;
}
int main()
{
43
Department of CS&E, BGSCET
EMP e;
int i, ch, n;
first=NULL;
while(1)
{
printf("nList Operationsn");
printf("===============n");
printf("1.Create a DLL of N Employees Data by using end insertionn");
printf("2.Display the status of DLL and count the number of nodes in itn");
printf("3.Perform Insertion and Deletion at End of DLLn");
printf("4.Perform Insertion and Deletion at Front of DLLn");
printf("5.Demonstration of this DLL as Double Ended Queuen");
printf("6.Exitn");
printf("Enter your choice : ");
scanf("%d",&i);
switch(i)
{
case 1 :
printf("Enter the number of Employeesn");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("nEnter the details of Employee %dn",i);
e=input();
addrear(e);
}
break;
case 2 :
if(first==NULL)
{
printf("List is Emptyn");
}
else
{
printf(" Node Count=%dt & Elements in the list are : n", count());
displayList();
}
break;
44
Department of CS&E, BGSCET
case 3 :
printf(" 1. Insert at End and 2 Delete From End=");
scanf("%d",&ch);
if(ch==1)
{
e=input();
addrear(e);
}
else if(ch==2)
deleterear();
else
printf(" Sorry wrong operationn");
break;
case 4 :
printf(" 1. Insert at Front and 2 Delete From Front=");
scanf("%d",&ch);
if(ch==1)
{
e=input();
addfront(e);
}
else if(ch==2)
deletefront();
else
printf(" Sorry wrong operationn");
break;
case 5:
printf("This DLL can be used as Double Ended Queue by inserting and deleting
from both ends n");
break;
case 6 :
return 0;
default : printf("Invalid optionn");
}
}
return 0;
}
45
Department of CS&E, BGSCET
Output:
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 1
Enter the number of Employees 2
Enter the details of Employee 1
Enter SSN: 111
Enter Name: Ram
Enter dept: Sales
Enter Designation :Manager
Enter Salary:50000
Enter Phone no : 9141000000
Enter the details of Employee 2
Enter SSN: 222
Enter Name: Sham
Enter dept: Design
Enter Designation :Manager
Enter Salary:60000
Enter Phone no : 9876543210
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 2
Node Count=2 & Elements in the list are :
46
Department of CS&E, BGSCET
SSN Name Dept Designation salary Phone
111 Ram Sales Manager 50000 9141000000
222 Sham Design Manager 60000 9876543210
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 3
1. Insert at End and 2 Delete From End=1
Enter SSN: 333
Enter Name: Ravi
Enter dept: Finance
Enter Designation :Manager
Enter Salary:65000
Enter Phone no : 9876500000
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 2
Node Count=3 & Elements in the list are :
SSN Name Dept Designation salary Phone
111 Ram Sales Manager 50000 9141000000
222 Sham Design Manager 60000 9876543210
333 Ravi Finance Manager 65000 9876500000
List Operations
===============
47
Department of CS&E, BGSCET
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 4
1. Insert at Front and 2 Delete From Front=2
SSN Name Dept Designation Salary Phone
111 Ram Sales Manager 50000 9141000000
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 2
Node Count=2 & Elements in the list are :
SSN Name Dept Designation salary Phone
222 Sham Design Manager 60000 9876543210
333 Ravi Finance Manager 65000 9876500000
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 5
This DLL can be used as Double Ended Queue by inserting and deleting from both ends
List Operations
===============
1.Create a DLL of N Employees Data by using end insertion
48
Department of CS&E, BGSCET
2.Display the status of DLL and count the number of nodes in it
3.Perform Insertion and Deletion at End of DLL
4.Perform Insertion and Deletion at Front of DLL
5.Demonstration of this DLL as Double Ended Queue
6.Exit
Enter your choice : 6
49
Department of CS&E, BGSCET
Program 9:
Develop a Program in C for the following operations on Singly Circular Linked List
(SCLL) with header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the
result in POLYSUM(x,y,z).
Support the program with appropriate functions for each of the above operations.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int coef,px,py,pz, x,y,z,i; int val;
struct node
{
int coef,px, py,pz; struct node *next;
};
typedef struct node NODE; NODE *first;
void insert(int coef,int px, int py, int pz)
{
NODE *temp,*cur;
temp= (NODE *)malloc(sizeof(NODE));
temp->coef=coef;
temp->px=px;
temp->py=py;
temp->pz=pz;
if(first==NULL)
{
temp->next=temp;
first=temp;
return;
}
if(first->next==first)
{
first->next=temp;
temp->next=first;
50
Department of CS&E, BGSCET
}
cur=first;
while(cur->next!=first)
{
cur=cur->next;
}
cur->next=temp;
temp->next=first;
return;
}
void display()
{
NODE *cur;
if(first==NULL)
{
printf("List is emptyn");
return;
}
cur=first;
while(cur->next!=first)
{
printf("%d ",cur->coef);
printf(" x^%d",cur->px);
printf(" y^%d",cur->py);
printf(" z^%d + ",cur->pz);
cur=cur->next;
}
printf("%d ",cur->coef);
printf(" x^%d",cur->px);
printf(" y^%d",cur->py);
printf(" z^%dn",cur->pz);
return;
}
int evaluate(int x, int y, int z)
{
NODE *cur; int v,s=0, v1,v2,v3;
if(first==NULL)
{
51
Department of CS&E, BGSCET
printf("List is emptyn");return 0;
}
cur=first;
while(cur->next!=first)
{
v=cur->coef*pow(x, cur->px)*pow(y, cur->py)*pow(z,cur->pz);
s=s+v;
cur=cur->next;
}
v=cur->coef*pow(x, cur->px)*pow(y, cur->py)*pow(z,cur->pz);
s=s+v;
return s;
}
int main()
{
int coef,px,py,pz, x,y,z,i;
int val;
first=NULL;
while(1)
{
printf("1. Insert polynomial at endn");
printf("2. Displayn");
printf("3. Evaluaten");
printf("4. Exitn");
printf("Enter Choice= t");
scanf("%d",&i);
switch(i)
{
case 1 : printf("Enter Coefficient= t");
scanf("%d",&coef);
printf("Enter powers of x y z values= t");
scanf("%d%d%d",&px, &py,&pz); insert(coef,px,py,pz);
break;
case 2 :
display();
break;
case 3 : printf("n Enter x y & z values for evaluation: t");
scanf("%d%d%d",&x,&y,&z);
52
Department of CS&E, BGSCET
val=evaluate(x,y,z);
printf("nValue=%dn",val);
break;
case 4 : return 0;
default : printf(" Wrong choice. Enter 1,2 3n");
break;
}
}
}
Output:
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 1
Enter Coefficient= 4
Enter powers of x y z values= 3 3 2
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 1
Enter Coefficient= 5
Enter powers of x y z values= 3 2 2
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 1
Enter Coefficient= 3
Enter powers of x y z values= 2 2 2
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 1
Enter Coefficient= 6
Enter powers of x y z values= 1 1 1
53
Department of CS&E, BGSCET
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 2
4 x^3 y^3 z^2 + 5 x^3 y^2 z^2 + 3 x^2 y^2 z^2 + 6 x^1 y^1 z^1
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 3
Enter x y & z values for evaluation: 3 2 1
Value=1548
1. Insert polynomial at end
2. Display
3. Evaluate
4. Exit
Enter Choice= 4
Program 9B
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node //Defining Polynomial fields
{
int coef, px, py, pz,flag;
struct node *link;
};
typedef struct node * NODE;
NODE create_list(NODE head) //For creating poly1 & poly2
{
int i,n,cf,px,py,pz;
printf("Enter the number of terms : ");
scanf("%d",&n);
54
Department of CS&E, BGSCET
for(i=1;i<=n;i++)
{
printf("Enter the Co-ef, px, py, pz : ");
scanf("%d %d %d %d",&cf,&px,&py,&pz);
insert(head,cf,px,py,pz);
}
return head;
}/*End of create_list()*/
insert(NODE head,int cof,int x,int y, int z) //inserting term to poly
{
NODE cur,tmp;
tmp= (NODE)malloc(sizeof(struct node)); //Allocates memory int cf,px,py,pz;
cur=head->link;
tmp->coef=cof;
tmp->px=x;
tmp->py=y;
tmp->pz=z;
tmp->flag=0;
while(cur->link!=head) //Identifying last node
cur=cur->link;
cur->link=tmp;
tmp->link=head;
}
NODE add_poly(NODE h1,NODE h2,NODE h3)
{
NODE cur1,cur2,scf; cur1=h1->link; cur2=h2->link;
while(cur1 != h1) //Till end of poly1
{
if(cur2 == h2)
cur2=h2->link;
while(cur2 != h2) //Till end of poly2
{
if(cur1->px == cur2->px && cur1->py == cur2->py && cur1->pz == cur2->pz)
{ //Add & insert if co-ef's of both poly is equal
scf = cur1->coef + cur2->coef;
insert(h3,scf,cur1->px,cur1->py,cur1->pz);
cur2->flag=1;
55
Department of CS&E, BGSCET
cur2=h2->link; break;
}
cur2=cur2->link;
}
if(cur1 == h1)
break;
if(cur2 == h2) //If co-ef of poly1 is not matched, insert it to poly3
insert(h3,cur1->coef,cur1->px,cur1->py,cur1->pz);
cur1=cur1->link;
}
cur2=h2->link;
while(cur2 != h2) //remaining poly2 nodes inserted to poly3
{
if(cur2->flag==0)
insert(h3,cur2->coef,cur2->px,cur2->py,cur2->pz);
cur2=cur2->link;
}
return h3;
}
void display(NODE head)
{
NODE cur;
if(head->link==head) //if poly is empty
{
printf("List is emptyn"); return;
}
cur=head->link;
while(cur != head) //display all terms till end
{
if(cur->coef > 0)
printf(" +%dx^%dy^%dz^%d ",cur->coef,cur->px,cur->py,cur->pz);
else if (cur->coef < 0)
printf(" %dx^%dy^%dz^%d ",cur->coef,cur->px,cur->py,cur->pz);
cur=cur->link;
}
printf("n");
}/*End of display() */
56
Department of CS&E, BGSCET
void main()
{
int choice,data,item,pos; NODE head1,head2,head3;
head1=(NODE)malloc(sizeof(struct node));
head1->link=head1; //poly1
head2=(NODE)malloc(sizeof(struct node));
head2->link=head2; //poly2
head3=(NODE)malloc(sizeof(struct node));
head3->link=head3; //poly3
printf("n1.Create Polynomial 1n");
head1=create_list(head1);
printf("n2.Create Polynomial 2n");
head2=create_list(head2);
printf("nPolynomial 1 is :");
display(head1);
printf("nPolynomial 2 is :");
display(head2);
head3=add_poly(head1,head2,head3); //Add both polynomials
printf("nAddition of two Polynomial is :");
display(head3);
}
Output:
1.Create Polynomial 1
Enter the number of terms : 4
Enter the Co-ef, px, py, pz : 5 3 3 3
Enter the Co-ef, px, py, pz : 6 3 3 2
Enter the Co-ef, px, py, pz : 8 2 2 2
57
Department of CS&E, BGSCET
Enter the Co-ef, px, py, pz : 9 1 0 1
2.Create Polynomial 2
Enter the number of terms : 4
Enter the Co-ef, px, py, pz : 6 3 3 3
Enter the Co-ef, px, py, pz : 5 2 2 2
Enter the Co-ef, px, py, pz : 8 2 1 2
Enter the Co-ef, px, py, pz : 9 1 1 0
Polynomial 1 is : +5x^3y^3z^3 +6x^3y^3z^2 +8x^2y^2z^2 +9x^1y^0z^1
Polynomial 2 is : +6x^3y^3z^3 +5x^2y^2z^2 +8x^2y^1z^2 +9x^1y^1z^0
Addition of two Polynomial is :
+6x^3y^3z^2 +9x^1y^0z^1 +6x^3y^3z^3 +5x^2y^2z^2 +8x^2y^1z^2 +9x^1y^1z^0
58
Department of CS&E, BGSCET
Program 10:
Develop a menu driven Program in C for the following operations on Binary Search Tree (BST)
of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int choice,data,key;
struct node
{
int info;
struct node *lchild,*rchild;
};
typedef struct node *NODE;
int main()
{
NODE root=NULL;
NODE CREATE(NODE,int);
void INORDER(NODE),POSTORDER(NODE),PREORDER(NODE);
NODE SEARCH_NODE(NODE,int);
while(1)
{
printf("n1:CREATEn2:TREE TRAVERSALn3.SEARCHn4.EXIT");
printf("nEnter your choicen");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("nEnter data to be insertedn");
scanf("%d",&data);
root=CREATE(root,data);
break;
case 2: if(root==NULL)
printf("nEMPTY TREEn");
else
59
Department of CS&E, BGSCET
{
printf("nThe Inorder display : ");
INORDER(root);
printf("nThe Preorder display : ");
PREORDER(root);
printf("nThe Postorder display : ");
POSTORDER(root);
}
break;
case 3: printf("nenter the key to search:n");
scanf("%d",&key);
SEARCH_NODE(root,key);
break;
case 4: exit(0);
}
}
}
NODE CREATE(NODE root,int data)
{
NODE newnode,x,parent;
newnode=(NODE)malloc(sizeof(struct node));
newnode->lchild=newnode->rchild=NULL;
newnode->info=data;
if(root==NULL)
root=newnode;
else
{
x=root;
while(x!=NULL)
{
parent=x;
if(x->info<data)
x=x->rchild; else if(x->info>data)
x=x->lchild;
else
{
printf("nNode is already present in the treen");
return(root);
}
60
Department of CS&E, BGSCET
}
if(parent->info<data)
parent->rchild=newnode;
else
parent->lchild=newnode;
}
return(root);
}
void INORDER(NODE root)
{
if(root!=NULL)
{
INORDER(root->lchild);
printf("%d ",root->info);
INORDER(root->rchild);
}
}
void PREORDER(NODE root)
{
if(root!=NULL)
{
printf("%d ",root->info);
PREORDER(root->lchild);
PREORDER(root->rchild);
}
}
void POSTORDER(NODE root)
{
if(root!=NULL)
{
POSTORDER(root->lchild);
POSTORDER(root->rchild);
printf("%d ",root->info);
}
}
NODE SEARCH_NODE(NODE root, int key)
{
61
Department of CS&E, BGSCET
NODE cur,q,parent,successor;
if(root==NULL)
{
printf("nTree is emptyn");
return root;
}
parent=NULL,cur=root;
while(cur!=NULL)
{
if(key==cur->info)
break;
parent=cur;
cur= (key<cur->info)?cur->lchild:cur->rchild;
}
if(cur==NULL)
{
printf("nData is not foundn");
return root;
}
printf("nData %d is foundn",key);
}
Output:
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
2
EMPTY TREE
62
Department of CS&E, BGSCET
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
6
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
9
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
5
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
63
Department of CS&E, BGSCET
2
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
8
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
15
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
24
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
64
Department of CS&E, BGSCET
Enter data to be inserted
14
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
7
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
8
Node is already present in the tree
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
1
Enter data to be inserted
5
Node is already present in the tree
1:CREATE
2:TREE TRAVERSAL
65
Department of CS&E, BGSCET
3.SEARCH
4.EXIT
Enter your choice
2
The Inorder display : 2 5 6 7 8 9 14 15 24
The Preorder display : 6 5 2 9 8 7 15 14 24
The Postorder display : 2 5 7 8 14 24 15 9 6
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
3
enter the key to search:
14
Data 14 is found
1:CREATE
2:TREE TRAVERSAL
3.SEARCH
4.EXIT
Enter your choice
3
enter the key to search:
4
Data is not found
66
Department of CS&E, BGSCET
Program 11:
Design, develop and implement a Program in C for the following operations on Graph (G) of
Cities Create a Graph of N cities using Adjacency Matrix. Print all the nodes reachable from a
given starting node in a digraph using BFS method
#include<stdio.h>
#include<stdlib.h>
int n,a[10][10],i,j,source,s[10],choice,count;
void bfs(int n,int a[10][10],int source,int s[]) //BFS Algorithm
{
int q[10],u;
int front=1,rear=1;
s[source]=1;
q[rear]=source;
while(front<=rear)
{
u=q[front];
front=front+1;
for(i=1;i<=n;i++)
if(a[u][i]==1 && s[i]==0)
{
rear=rear+1;
q[rear]=i;
s[i]=1;
}
}
}
int main()
{
printf("Enter the number of nodes : ");
scanf("%d",&n);
printf("n Enter the adjacency matrixn");
for(i=1;i<=n;i++) //Provide matrix of 0’s and 1’s
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
67
Department of CS&E, BGSCET
while(1)
{
printf("nEnter your choicen");
printf("1.BFSn 2.Exitn");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("n Enter the source :");
scanf("%d",&source); //Provide source for BFS
for(i=1;i<=n;i++)
s[i]=0;
bfs(n,a,source,s);
for(i=1;i<=n;i++)
{
if(s[i]==0)
printf("n The node %d is not reachable",i);
else
printf("n The node %d is reachable",i);
}
break;
case 2:
exit(0);
}
}
}
Output:
Enter the number of nodes : 5
Enter the adjacency matrix
68
Department of CS&E, BGSCET
0 1 0 1 0
0 0 1 0 0
1 0 0 0 0
0 0 1 0 0
0 0 1 1 0
Enter your choice
1.BFS
2.Exit
1
Enter the source :5
The node 1 is reachable
The node 2 is reachable
The node 3 is reachable
The node 4 is reachable
The node 5 is reachable
Enter your choice
1.BFS
2.Exit
1
Enter the source :1
The node 1 is reachable
69
Department of CS&E, BGSCET
The node 2 is reachable
The node 3 is reachable
The node 4 is reachable
The node 5 is not reachable
Enter your choice
1.BFS
2.Exit
2
70
Department of CS&E, BGSCET
PROGRAM 12:
Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the
records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory
locations with L as the set of memory addresses (2-digit) of locations in HT. Let the keys in K and
addresses in L are Integers.
Develop a Program in C that uses Hash function H: K →L as H(K)=K mod m (remainder method),
and implement hashing technique to map a given key K to the address space L. Resolve the
collision (if any) using linear probing.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
#define mod(x) x%MAX
void linear_prob(int a[],int num,int key)
{
if(a[key]==-1)
a[key]=num;
else
{
printf("nCollision detected!!");
int i;
for(i=mod(key+1);i!=key;i=mod(++i))
if(a[i]==-1)
break;
if(i!=key)
{
printf("nCollision avoided successfullyn");
a[i]=num;
}
else
printf("nHash table is fulln");
}
}
void display(int a[])
{
short ch,i;
printf("n1.Filtered displayn2.Display allnEnter choice:");
scanf("%hd",&ch);
71
Department of CS&E, BGSCET
printf("nHash table is :n");
for(i=0;i<MAX;i++)
if(a[i]>0||ch-1)
printf("%d %dn",i,a[i]);
}
int main()
{
int a[MAX],num,i;
printf("nCollision handling by linear probing");
for(i=0;i<MAX;a[i++]=-1);
do
{
printf("nEnter the data:");
scanf("%4d",&num);
linear_prob(a,num,mod(num));
printf("Do u wish to continue(1/0):");
scanf("%d",&i);
}while(i);
display(a);
return 0;
}
Output:
Collision handling by linear probing
Enter the data:5
Do u wish to continue(1/0):1
Enter the data:4
Do u wish to continue(1/0):1
Enter the data:3
Do u wish to continue(1/0):0
1.Filtered display
2.Display all
Enter choice:1
Hash table is :
0 5
3 3
72
Department of CS&E, BGSCET
Appendix A
SAMPLE PROGRAMS ON DATA STRUCTURES
Program 1
Write a C program to implement pointer operations.
// Program to implement pointer operations
#include<stdio.h>
#include<conio.h
> void main()
{
int i_num =3, *i_ptr=&i_num;
clrscr();
printf("nAddress of i_num=0X%x",&i_num);
printf("nAddress of i_num=0X%x",i_ptr);
printf("nAddress of i_ptr=0X%x",&i_ptr);
printf("nAddressof i_num through pointer=0X%x",i_ptr);
printf("nValue of i_num=%d",i_num);
printf("nValue of i_num through pointer symbols=%d",*(&i_num));
printf("nValue of I through pointer=%d",*i_ptr);
getch();
}
Program2
Write a C program to exchange two values using pointers.
// Program to exchange two values
#include<stdio.h>
#include<conio.h
> void main()
73
Department of CS&E, BGSCET
{
int i_num1, i_num2;
void swap(int*, int*);
clrscr();
printf("Enter 2 integersn");
scanf("%d%d", &i_num1, &i_num2);
printf("Values before swapping are %d and %dnn",i_num1,i_num2);
swap(&i_num1,&i_num2);
printf("Values after swapping are %d and %dnn",i_num1,i_num2);
getch();
}
void swap(int *x,int *y)
{
int temp =*x;
*x=*y;
*y=temp;
}
Program 3
Write a program to create a structure named student with variables book ID,
name and price. Create a variable of type structure, initialize the details and
print them on the screen.
74
Department of CS&E, BGSCET
// Program to implement structure
#include <stdio.h>
#include
<conio.h> struct
book
{ int
i_book
_id;
char
*c_na
me;
float
f_price
;
} b;
void main()
{
clrscr();
b.i_book_id
=1;
b.c_name = "Fundamentals of Data
Structure"; b.f_price = 390.5;
printf("Book Id is : %d n",
b.i_book_id); printf("Name is : %s
n", b.c_name); printf("Price is : %f
n", b.f_price); getch();
}
75
Department of CS&E, BGSCET
APPENDIX B:
VIVA QUESTIONS WITH
ANSWERS
1. What is data structure?
A data structure is a way of organizing data that considers not only the items stored, but also their
relationship to each other.
2. List out the areas in which data structures are applied extensively?
· Compiler Design
· Operating System
· Database Management System
· Statistical analysis package
· Numerical Analysis
· Graphics
· Artificial Intelligence
· Simulation
3. What are the major data structures used in the following areas: RDBMS, Network data
model and Hierarchical data model?
· RDBMS = Array (i.e. Array of structures)
· Network data model = Graph
· Hierarchical data model = Trees
4. What is the Minimum number of queues needed to implement the priority queue?
Two. One queue is used for actual storing of data and another for storing priorities.
5. What is the data structures used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom
to return when the function has to return.
6. In tree construction which is the suitable efficient data structure? (Array, Linked list,
Stack, Queue)
Linked list is the suitable efficient data structure.
76
Department of CS&E, BGSCET
7. What is the significant difference between ARRAY and STACK?
Stack uses LIFO. Thus the item that is certainly first entered would be the last removed. In
array the items could be entered or removed in any order. Basically each and every member
access is done making use of index and no strict order is to be followed here to remove a
particular element. Array could be multi-dimensional or one dimensional but stack really should
be one-dimensional. Size of array is fixed, while stack may be grow or shrink. We can say stack
is actually dynamic data structure.
8. Explain whether Linked List is actually linear or Non-linear data structure? Link list is
definitely obviously linear data structure simply because each and every element (NODE)
acquiring specific place and as well each and every component has got its unique successor in
addition to predecessor.
9. What is the difference between a Stack and a Queue?
Stack follows LIFO (Last In First Out) method of accessing the members. Queue
follows FIFO (First In First Out) method of accessing the members.
10. What is a one way chain or singly linked linear list?
Singly linked list is a collection of nodes. Each node has element and address of the next element.
With that address only forward traversal is possible i.e. single link
11. How can a node be inserted in the middle of a linked list?
By repointing the previous and the next elements of existing nodes to the new node.
11. What is the heap?
The heap is where malloc(), calloc(), and realloc() get memory.
12. Which data structure is needed to convert infix notations to post fix
notations?
Stack
13. List out few of the applications that make use of Multilinked Structures?
· Sparse matrix.
· Index generation.
14. In tree construction which is the suitable efficient data structure?
Linked List
77
Department of CS&E, BGSCET
15. What is the evaluation order according to which an infix expression is converted
to postfix expression?
The evaluation order is:
· Brackets or Parenthesis,
· Exponentiation,
· Multiplication or division,
· Addition or subtraction.
16. Give the advantages of using post fix notations over infix notations?
An infix expression is evaluated keeping in mind the precedence of operators. An infix
expression is difficult for the machine to know and keep track of precedence of operators. A
postfix expression itself takes care of the precedence of operators as the placement of operators.
Thus, for the machine, it is easier to carry out a postfix expression than an infix expression.
17. List out few of the Application of tree data-structure?
The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis.
18. In RDBMS, what is the efficient data structure used in the internal storage
representation?
B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching
easier. This corresponds to the records that shall be stored in leaf nodes.
19. Why do we Use a Multidimensional Array?
A multidimensional array can be useful to organize subgroups of data within an array.
20. Run Time Memory Allocation is known as?
Allocating memory at runtime is called a dynamically allocating memory. In this, you
dynamically allocate memory by using the new operator when declaring the array, for
example: int grades [] = new int [10];

More Related Content

Similar to vtu data structures lab manual bcs304 pdf

CS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviCS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviSELVI SIVAPERUMAL
 
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manualpkaviya
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoepandhari
 
Cs8581 networks lab manual 2017
Cs8581 networks lab manual   2017Cs8581 networks lab manual   2017
Cs8581 networks lab manual 2017Kayathri Devi D
 
IT6611 Mobile Application Development Lab Manual
IT6611 Mobile Application Development Lab ManualIT6611 Mobile Application Development Lab Manual
IT6611 Mobile Application Development Lab Manualpkaviya
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfSuperBoy40
 
Digital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdfDigital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdfAmairullahKhanLodhi1
 
B tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEB tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEMITAcademy1
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSRPatel10
 
01.B.E. CSE final.doc
01.B.E. CSE final.doc01.B.E. CSE final.doc
01.B.E. CSE final.doctsajuraj
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEMITAcademy1
 
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...shohi1
 
CS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory ManualCS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory ManualMuthu Vinayagam
 
Report[Batch-08].pdf
Report[Batch-08].pdfReport[Batch-08].pdf
Report[Batch-08].pdf052Sugashk
 
(Final)Computer Architecture.docx
(Final)Computer Architecture.docx(Final)Computer Architecture.docx
(Final)Computer Architecture.docxRechieJohnRelator
 

Similar to vtu data structures lab manual bcs304 pdf (20)

CS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviCS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.Selvi
 
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manual
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeo
 
Dc course file
Dc course fileDc course file
Dc course file
 
Cs8581 networks lab manual 2017
Cs8581 networks lab manual   2017Cs8581 networks lab manual   2017
Cs8581 networks lab manual 2017
 
IT6611 Mobile Application Development Lab Manual
IT6611 Mobile Application Development Lab ManualIT6611 Mobile Application Development Lab Manual
IT6611 Mobile Application Development Lab Manual
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdf
 
IT6511 Networks Laboratory
IT6511 Networks LaboratoryIT6511 Networks Laboratory
IT6511 Networks Laboratory
 
Digital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdfDigital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdf
 
B tech cse syllabus - MITAOE
B tech cse syllabus - MITAOEB tech cse syllabus - MITAOE
B tech cse syllabus - MITAOE
 
01.b.e. cse final
01.b.e. cse final01.b.e. cse final
01.b.e. cse final
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
 
01.B.E. CSE final.doc
01.B.E. CSE final.doc01.B.E. CSE final.doc
01.B.E. CSE final.doc
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOE
 
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
 
2017 BE CSE Syllabus Anna University Affiliated Colleges
2017 BE CSE Syllabus Anna University Affiliated Colleges2017 BE CSE Syllabus Anna University Affiliated Colleges
2017 BE CSE Syllabus Anna University Affiliated Colleges
 
CS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory ManualCS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory Manual
 
Report[Batch-08].pdf
Report[Batch-08].pdfReport[Batch-08].pdf
Report[Batch-08].pdf
 
(Final)Computer Architecture.docx
(Final)Computer Architecture.docx(Final)Computer Architecture.docx
(Final)Computer Architecture.docx
 

Recently uploaded

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

vtu data structures lab manual bcs304 pdf

  • 1. ||Jai Sri Gurudev|| BGSKH Education Trust BGS COLLEGE OF ENGINEERING AND TECHNOLOGY MAHALAKSHMIPURAM, BENGALURU - 560086 Data Structures Lab Manual For third Semester BE [VTU/CBCS, 2022 Scheme] Subject Code: Name: ……………………………………………………..…. Branch: ………………………………………………….…… USN: ……………………………….……………………….… B C S L 3 0 5
  • 2. i PREFACE C programming language offers several facilities to group data together in convenient packages, or data structures. With the emergence of C as the most popular language of implementation blossomed from Bell laboratories. This book for practical “Data Structures laboratory” is an introduction to all popular data structures and their implementation with the C language. It is planned for beginners who would like to learn the subject through programs. This edition emphasizes on abstract concepts of Data Structures and describes how these are useful in problem solving using structures such as queues, arrays, linked lists, stacks, trees and graphs. Students will gain a good appreciation of the subject as this book has a clear display of syntax and elegant programming examples. To simplify concepts, the data structures are implemented using C language, in a step-by-step manner. BGS College of Engineering & Technology Department of Computer Science and Engineering Vision Nurturing young minds to making them industry ready IT professionals Mission M1: Providing strong foundational knowledge of mathematics, science, and computational approaches on solving theoretical and practical problems of Computer Science. M2: Imparting high quality advanced knowledge in experiential learning to get expertise in modern software tools and to cater to the real time requirements of the industry. M3: Fostering the professionalism to achieve goals by inculcating niche skills for Successful Entrepreneur M4: Provide a conducive environment to train students in progressive and convergent research themes. M5: Inculcate problem solving and team building skills and promote lifelong learning with a sense of societal and value based ethical responsibilities PROGRAM EDUCATIONAL OBJECTIVES PEO1: Graduates will be able to demonstrate technical competency and leadership by accomplishing Engineering knowledge, mathematics, science & engineering fundamentals.
  • 3. ii PEO2: Graduates will be able to analyse and understand current pedagogical techniques, industry accepted computing practices and state-of-art technology to deliver solutions by creative intuitions towards technological growth and societal needs. PEO3: Graduates will be able to exhibit cultural awareness, teamwork with professional ethics, effective communication skills and leader qualities to achieve higher career goals. PEO4: Graduates will be able to pursue higher education in pursuit of lifelong learning and explore the research possibilities, entrepreneurship opportunities and novel innovation practices. PROGRAM SPECIFIC OUTCOMES PSO1: Demonstrate the use of knowledge and ability to develop applications and integrate them in the areas related to Databases, Web programming, Artificial Intelligence and machine learning, Data Science, and allied areas. PSO2: Identify the various analysis & design methodologies for facilitating development of effective algorithms and code for high quality system software products with focus on performance optimization. PSO3: Develop the capability of comprehending the technological advancements in the practice of modern design tools in planning and implementing solutions to cater to business – specific requirements exhibiting team dynamics and professional ethics.
  • 4. iii PROGRAM OUTCOMES (POs) Engineering Graduates will be able to: 1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering specialization to the solution of complex engineering problems. 2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences. 3. Design/development of solutions: Design solutions for complex engineering problems and design system components or processes that meet the specified needs with appropriate consideration for the public health and safety, and the cultural, societal, and environmental considerations. 4. Conduct investigations of complex problems: Use research-based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions. 5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations. 6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice. 7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
  • 5. iv 8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice. 9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings. 10. Communication: Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and receive clear instructions. 11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments. 12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest context of technological change.
  • 6. v INDEX Sl.No Contents Page No 1 Lab assessment rubrics for CIE ix 2 Develop a Program in C for the following: a) Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days of a week. Each Element of the array is a structure having three fields. The first field is the name of the Day (A dynamically allocated String), The second field is the date of the Day (A integer), the third field is the description of the activity for a particular day (A dynamically allocated String). b) Write functions create(), read() and display(); to create the calendar, to read the data from the keyboard and to print weeks activity details report on screen. 1 3 Develop a Program in C for the following operations on Strings. a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP) b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR Support the program with functions for each of the above operations. Don't use Built-in functions. 4 4 Develop a menu driven Program in C for the following operations on STACK of Integers (Array Implementation of Stack with maximum size MAX) a. Push an Element on to Stack b. Pop an Element from Stack c. Demonstrate how Stack can be used to check Palindrome d. Demonstrate Overflow and Underflow situations on Stack e. Display the status of Stack f. Exit Support the program with appropriate functions for each of the above operations 6 5 Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands. 16 6 Develop a Program in C for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^ b. Solving Tower of Hanoi problem with n disks 19 7 Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters (Array 23
  • 7. vi Implementation of Queue with maximum size MAX) a. Insert an Element on to Circular QUEUE b. Delete an Element from Circular QUEUE c. Demonstrate Overflow and Underflow situations on Circular QUEUE d. Display the status of Circular QUEUE e. Exit Support the program with appropriate functions for each of the above operations 8 Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of Student Data with the fields: USN, Name, Programme, Sem, PhNo a. Create a SLL of N Students Data by using front insertion. b. Display the status of SLL and count the number of nodes in it c. Perform Insertion / Deletion at End of SLL d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack) e. Exit 28 9 Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo a. Create a DLL of N Employees Data by using end insertion. b. Display the status of DLL and count the number of nodes in it c. Perform Insertion and Deletion at End of DLL d. Perform Insertion and Deletion at Front of DLL e. Demonstrate how this DLL can be used as Double Ended Queue. f. Exit 38 10 Develop a Program in C for the following operationson Singly Circular Linked List (SCLL) with header nodes a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2 y2 z-4yz5 +3x2 yz+2xy5 z-2xyz3 b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in POLYSUM(x,y,z) Support the program with appropriate functions for each of the above operations 49 11 Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers . a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2 b. Traverse the BST in Inorder, Preorder and Post Order c. Search the BST for a given element (KEY) and report the appropriate message d. Exit 58
  • 8. vii 12 Develop a Program in C for the following operations on Graph(G) of Cities a. Create a Graph of N cities using Adjacency Matrix. b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS method 66 13 Given a File of N employee records with a set K of Keys (4- digit) which uniquely determine the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory locations with L as the set of memory addresses (2- digit) of locations in HT. Let the keys in K and addresses in L are Integers. Develop a Program in C that uses Hash function H: K →L as H(K)=K mod m (remainder method), and implement hashing technique to map a given key K to the address space L. Resolve the collision (if any) using linear probing. 70 14 Appendix A 72 15 Appendix B 75 Laboratory Outcomes: The student should be able to: ● Analyze various linear and non-linear data structures. ● Demonstrate the working nature of different types of data structures and their applications ● Use appropriate searching and sorting algorithms for the given scenario. ● Apply the appropriate data structure for solving real world problems. Conduct of Practical Examination: ● Experiment distribution ○ For laboratories having only one part: Students are allowed to pick one experiment from the lot with equal opportunity. ○ For laboratories having PART A and PART B: Students are allowed to pick one experiment from PART A and one experiment from PART B, with equal opportunity. ● Change of experiment is allowed only once and marks allotted for procedure to be made zero of the changed part only. ● Marks Distribution (Need to change in accordance with university regulations) ○ For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 = 100 Marks
  • 9. viii ○ For laboratories having PART A and PART B ■ Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks ■ Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks Course objectives: CO1 Analyze various linear and non-linear data structures CO2 Demonstrate the working nature of different types of data structures and their applications CO3 Use appropriate searching and sorting algorithms for the give scenario. CO4 Apply the appropriate data structure for solving real world problems PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO1 1 PO12 CO1 3 - 3 - - - - - - - - - CO2 2 2 3 - - - - - - - - - CO3 2 2 3 - - - - - - - - - CO4 - - - - - - - - 2 2 - -
  • 10. ix Lab Assessment Rubrics for CIE Sl No Description Marks 1 Continuous Evaluation 30 a. Observation write up and punctuality 5 b. Conduction of experiment and output 10 c. Viva voice 5 d. Record write up 10 2 Internal Test 20
  • 11. 1 Department of CS&E, BGSCET Program 1: Develop a Program in C for the following: a) Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days of a week. Each Element of the array is a structure having three fields. The first field is the name of the Day (A dynamically allocated String), The second field is the date of the Day (A integer), the third field is the description of the activity for a particular day (A dynamically allocated String). b) Write functions create(), read() and display(); to create the calendar, to read the data from the keyboard and to print weeks activity details report on screen. #include <stdio.h> #include <stdlib.h> #include <string.h> // Define the structure for each day of the week struct Day { char *name; int date; char *activity; }; // Define an array to store 7 days of the week struct Day week[7]; // Function to create the calendar void create() { for (int i = 0; i < 7; i++) { week[i].name = (char *)malloc(20 * sizeof(char)); week[i].activity = (char *)malloc(100 * sizeof(char)); printf("Enter the name of day %d: ", i + 1); scanf("%s", week[i].name); printf("Enter the date of day %d: ", i + 1); scanf("%d", &week[i].date); printf("Enter the activity for day %d: ", i + 1); getchar(); // Consume the newline character fgets(week[i].activity, 100, stdin); } } // Function to read data from the keyboard void read() { create(); // Reusing the create function for reading data
  • 12. 2 Department of CS&E, BGSCET } // Function to display the calendar void display() { printf("nDaytDatetActivityn"); for (int i = 0; i < 7; i++) { printf("%st%dt%s", week[i].name, week[i].date, week[i].activity); } } int main() { printf("Creating a calendar:n"); create(); printf("nDisplaying the calendar:n"); display(); return 0; } Output: Creating a calendar: Enter the name of day 1: Monday Enter the date of day 1: 30 Enter the activity for day 1: 3rd Sem starts Enter the name of day 2: Tuesday Enter the date of day 2: 31 Enter the activity for day 2: Interaction with juniors Enter the name of day 3: Wednesday Enter the date of day 3: 1 Enter the activity for day 3: Kannada Rajyotsava Enter the name of day 4: Thursday Enter the date of day 4: 2 Enter the activity for day 4: Technical Talk from Industry Experts Enter the name of day 5: Friday Enter the date of day 5: 3 Enter the activity for day 5: Cultural Activities Enter the name of day 6: Saturday
  • 13. 3 Department of CS&E, BGSCET Enter the date of day 6: 4 Enter the activity for day 6: Hands on session (Web Designing) Enter the name of day 7: Saturday Enter the date of day 7: 5 Enter the activity for day 7: Refreshment Displaying the calendar: Day Date Activity Monday 30 3rd Sem starts Tuesday 31 Interaction with juniors Wednesday 1 Kannada Rajyotsava Thursday 2 Technical Talk from Industry Experts Friday 3 Cultural Activities Saturday 4 Hands on session (Web Designing) Sunday 5 Refreshment
  • 14. 4 Department of CS&E, BGSCET Program 2 Develop a Program in C for the following operations on Strings. a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP) b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR Support the program with functions for each of the above operations. Don't use Built-in functions. #include<stdio.h> char str[50], pat[20], rep[20], ans[50]; int c=0, m=0, i=0, j=0, k, flag=0; void stringmatch() { while(str[c] !='0') { if(str[m] == pat[i]) { i++; m++; if(pat[i] == '0') { flag = 1; for(k=0; rep[k]!='0'; k++, j++) { ans[j] = rep[k]; } i = 0; c = m; } } else { ans[j]= str[c]; j++; c++;
  • 15. 5 Department of CS&E, BGSCET m=c; i=0; } } ans[j]='0'; } void main() { printf("nEnter the main string:"); gets(str); printf("nEnter the pat string:"); gets(pat); printf("nEnter the replace string:"); gets(rep); stringmatch(); if(flag == 1) printf("nResultant string is %s", ans); else printf("nPattern string is not found"); } Output: Enter the main string: Welcome to BGSgroups Enter the pat string: groups Enter the replace string: CET Resultant string is Welcome to BGSCET
  • 16. 6 Department of CS&E, BGSCET Program 3: Develop a menu driven Program in C for the following operations on STACK of Integers (Array Implementation of Stack with maximum size MAX) a. Push an Element on to Stack b. Pop an Element from Stack c. Demonstrate how Stack can be used to check Palindrome d. Demonstrate Overflow and Underflow situations on Stack e. Display the status of Stack f. Exit Support the program with appropriate functions for each of the above operations. #include<stdio.h> #include<stdlib.h> #define MAX 5 int s[MAX]; int top = -1; void push(int item); int pop(); void palindrome(); void display(); void main() { int choice, item; while(1) { printf("nnnn~~~~~~Menu~~~~~~ : "); printf("n=>1.Push an Element to Stack and Overflow demo "); printf("n=>2.Pop an Element from Stack and Underflow demo"); printf("n=>3.Palindrome demo "); printf("n=>4.Display "); printf("n=>5.Exit"); printf("nEnter your choice: "); scanf("%d", &choice); switch(choice) {
  • 17. 7 Department of CS&E, BGSCET case 1: printf("nEnter an element to be pushed: "); scanf("%d", &item); push(item); break; case 2: item = pop(); if(item != -1) printf("nElement popped is: %d", item); break; case 3: palindrome(); break; case 4: display(); break; case 5: exit(1); default: printf("nPlease enter valid choice ") ; break; } } } void push(int item) { if(top == MAX-1) { printf("n~~~~Stack overflow~~~~"); return; } top = top + 1 ; s[top] = item; } int pop() { int item;
  • 18. 8 Department of CS&E, BGSCET if(top == -1) { printf("n~~~~Stack underflow~~~~"); return -1; } item = s[top]; top = top - 1; return item; } void display() { int i; if(top == -1) { printf("n~~~~Stack is empty~~~~"); return; } printf("nStack elements are:n "); for(i=top; i>=0 ; i--) printf("| %d |n", s[i]); } void palindrome() { int flag=1,i; printf("nStack content are:n"); for(i=top; i>=0 ; i--) printf("| %d |n", s[i]); printf("nReverse of stack content are:n"); for(i=0; i<=top; i++) printf("| %d |n", s[i]);
  • 19. 9 Department of CS&E, BGSCET for(i=0; i<=top/2; i++) { if( s[i] != s[top-i] ) { flag = 0; break; } } if(flag == 1) { printf("nIt is palindrome number"); } else { printf("nIt is not a palindrome number"); } } Output: ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 25
  • 20. 10 Department of CS&E, BGSCET ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 26 ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 27 ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 28
  • 21. 11 Department of CS&E, BGSCET ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 4 Stack elements are: | 28 | | 27 | | 26 | | 25 | ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 2 Element popped is: 28 ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo
  • 22. 12 Department of CS&E, BGSCET =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 4 Stack elements are: | 27 | | 26 | | 25 | ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 3 Stack content are: | 27 | | 26 | | 25 | Reverse of stack content are: | 25 | | 26 | | 27 | It is not a palindrome number
  • 23. 13 Department of CS&E, BGSCET ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 5 Output 2: ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 1 ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 2 ~~~~~~Menu~~~~~~ :
  • 24. 14 Department of CS&E, BGSCET =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 1 Enter an element to be pushed: 1 ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 4 Stack elements are: | 1 | | 2 | | 1 | ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 3
  • 25. 15 Department of CS&E, BGSCET Stack content are: | 1 | | 2 | | 1 | Reverse of stack content are: | 1 | | 2 | | 1 | It is palindrome number ~~~~~~Menu~~~~~~ : =>1.Push an Element to Stack and Overflow demo =>2.Pop an Element from Stack and Underflow demo =>3.Palindrome demo =>4.Display =>5.Exit Enter your choice: 5
  • 26. 16 Department of CS&E, BGSCET Program 4: Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands. #include <ctype.h> #include <stdio.h> #define SIZE 50 /* Size of Stack */ char s[SIZE]; /* Global declarations */ int top = -1; push(char elem) /* Function for PUSH operation */ { s[++top] = elem; } char pop() /* Function for POP operation */ { return (s[top--]); } int pr(char elem) /* Function for precedence */ { switch (elem) { case '#': return 0; case '(': return 1; case '+': case '-': return 2; case '*': case '/': case '%': return 3; case '^': return 4; } } void main() /* Main Program */ {
  • 27. 17 Department of CS&E, BGSCET char infx[50], pofx[50], ch, elem; int i = 0, k = 0; printf("nn enter the Infix Expression : "); gets(infx); push('#'); while ((ch = infx[i++]) != '0') { if (ch == '(') push(ch); else if (isalnum(ch)) pofx[k++] = ch; else if (ch == ')') { while (s[top] != '(') pofx[k++] = pop(); elem = pop(); /* Remove ( */ } else /* Operator */ { while (pr(s[top]) >= pr(ch)) pofx[k++] = pop(); push(ch); } } while (s[top] != '#') /* Pop from stack till empty */ pofx[k++] = pop(); pofx[k] = '0'; /* Make pofx as valid string */ printf("nn Given Infix Expn is: %sn The Postfix Expn is:%sn", infx, pofx); } Output 1: enter the Infix Expression : a+b-c*d Given Infix Expn is: a+b-c*d The Postfix Expn is: ab+cd*-
  • 28. 18 Department of CS&E, BGSCET Output 2: enter the Infix Expression : a+(b-c)*d/e^f Given Infix Expn is: a+(b-c)*d/e^f The Postfix Expn is:abc-d*ef^
  • 29. 19 Department of CS&E, BGSCET Program 5: Develop a Program in C for the following Stack Applications a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^ #include<stdio.h> #include<stdlib.h> #include<math.h> int i, top = -1; int op1, op2, res, s[20]; char postfix[90], symb; void push(int item) { top = top+1; s[top] = item; } int pop() { int item; item = s[top]; top = top-1; return item; } void main() { printf("nEnter a valid postfix expression:n"); scanf("%s", postfix); for(i=0; postfix[i]!='0'; i++) { symb = postfix[i]; if(isdigit(symb))
  • 30. 20 Department of CS&E, BGSCET { push(symb - '0'); } else { op2 = pop(); op1 = pop(); switch(symb) { case '+': push(op1+op2); break; case '-': push(op1-op2); break; case '*': push(op1*op2); break; case '/': push(op1/op2); break; case '%': push(op1%op2); break; case '$': case '^': push(pow(op1, op2)); break; default : push(0); } } } res = pop(); printf("n Result = %d", res); } Output: Enter a valid postfix expression: 651-4*23$/+
  • 31. 21 Department of CS&E, BGSCET Result = 8 Output 2: Enter a valid postfix expression: 861-*2/32^% Result = 2 b. Solving Tower of Hanoi problem with n disks #include<stdio.h> #include<conio.h> int count=0,n; int tower(int n,char s,char t,char d) { if(n==1) { printf("n Move disc 1 from %c to %c",s,d); count++; return 1; } tower(n-1,s,d,t); printf("n Move disc %d from %c to %c",n,s,d); count++; tower(n-1,t,s,d); } int main( ) { printf("n Enter the no. of discs:"); scanf("%d",&n); tower(n,'A','B','C'); printf("n The no. of disc moves is:%d",count); getch( ); }
  • 32. 22 Department of CS&E, BGSCET Output 1: Enter the no. of discs:2 Move disc 1 from A to B Move disc 2 from A to C Move disc 1 from B to C The no. of disc moves is:3 Output 2: Enter the no. of discs:4 Move disc 1 from A to B Move disc 2 from A to C Move disc 1 from B to C Move disc 3 from A to B Move disc 1 from C to A Move disc 2 from C to B Move disc 1 from A to B Move disc 4 from A to C Move disc 1 from B to C Move disc 2 from B to A Move disc 1 from C to A Move disc 3 from B to C Move disc 1 from A to B Move disc 2 from A to C Move disc 1 from B to C The no. of disc moves is: 15
  • 33. 23 Department of CS&E, BGSCET Program 6: Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX) a. Insert an Element onto Circular QUEUE b. Delete an Element from Circular QUEUE c. Demonstrate Overflow and Underflow situations on Circular QUEUE d. Display the status of Circular QUEUE e. Exit Support the program with appropriate functions for each of the above operations. #include<stdio.h> #include<conio.h> #include<stdlib.h> #define SIZE 5 int q[SIZE], i, r=-1, f=0, option, count=0, j; int main( ) { for(;;) { printf("n 1.Insert 2.Deleten 3.Display 4.Exit"); printf("nEnter your option:"); scanf("%d",&option); switch(option) { case 1: //Inserting items to Queue if(count==SIZE) printf("n Q is Fulln"); else { r=(r+1)%SIZE; printf("nEnter the item:"); scanf("%d",&q[r]); count++; } break; case 2: //Deleting items from Queue if(count==0)
  • 34. 24 Department of CS&E, BGSCET printf("nQ is emptyn"); else { printf("nDeleted item is: %d",q[f]); count--; f=(f+1)%SIZE; } break; case 3: //Displaying items from Queue if(count==0) printf("nQ is Emptyn"); else { i=f; for(j=0;j<count;j++) { printf(" %d",q[i]); i=(i+1)%SIZE; } } break; default: exit(0); } } } Output: 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:10
  • 35. 25 Department of CS&E, BGSCET 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:20 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:30 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:40 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:50 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Q is Full
  • 36. 26 Department of CS&E, BGSCET 1.Insert 2.Delete 3.Display 4.Exit Enter your option:3 10 20 30 40 50 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Deleted item is: 10 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Deleted item is: 20 1.Insert 2.Delete 3.Display 4.Exit Enter your option:3 30 40 50 1.Insert 2.Delete 3.Display 4.Exit Enter your option:1 Enter the item:60 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Deleted item is: 30 1.Insert 2.Delete
  • 37. 27 Department of CS&E, BGSCET 3.Display 4.Exit Enter your option:2 Deleted item is: 40 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Deleted item is: 50 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Deleted item is: 60 1.Insert 2.Delete 3.Display 4.Exit Enter your option:2 Q is empty
  • 38. 28 Department of CS&E, BGSCET Program 7: Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of Student Data with the fields: USN, Name, Programme, Sem, PhNo a. Create a SLL of N Students Data by using front insertion. b. Display the status of SLL and count the number of nodes in it. c. Perform Insertion / Deletion at End of SLL d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack) e. Exit #include<stdio.h> #include<stdlib.h> #include<string.h> struct student { char usn[11]; char name[25]; int sem; char branch[5]; unsigned long long phno; }; typedef struct student STUD; struct node { char usn[11]; char name[25]; int sem; char branch[5]; unsigned long long phno; struct node *next; }; typedef struct node NODE; NODE *first; NODE* copyNode(STUD s) { NODE * temp;
  • 39. 29 Department of CS&E, BGSCET temp= (NODE *)malloc(sizeof(NODE)); if(temp==NULL) { printf("Memory cannot be allocatedn"); } else { strcpy(temp->usn,s.usn); strcpy(temp->name, s.name); strcpy(temp->branch, s.branch); temp->sem=s.sem; temp->phno=s.phno; temp->next=NULL; return temp; } } void addrear(STUD s) { NODE *temp,*cur; temp=copyNode(s) ; if(first==NULL) { temp=first; return; } cur=first; while(cur->next != NULL) { cur=cur->next; } cur->next =temp; return ; } void addfront(STUD s)
  • 40. 30 Department of CS&E, BGSCET { NODE *temp; temp=copyNode(s); //ssn,name, dept, design,salary, pno); if (first== NULL) { first=temp; } else { temp->next=first; first=temp; } return ; } void display(NODE *temp) { printf("%s t", temp->usn); printf("%s t", temp->name); printf("%s t", temp->branch); printf("%d t",temp->sem); printf("%llu n", temp->phno); } void deletefront() { NODE *temp; int num; temp=first; if(first==NULL) { printf("List is Empty"); return; } if(first->next==NULL)
  • 41. 31 Department of CS&E, BGSCET first=NULL; else { first=first->next; } printf("Deleted Node is:n"); display(temp); free(temp); return; } void deleterear() { NODE *cur,*prev; cur=first; prev=NULL; if(first==NULL) { printf("List is Empty"); return; } if(first->next==NULL) { display(cur); first=NULL; free(cur); return; } while(cur->next!=NULL) { prev=cur; cur=cur->next; } prev->next=NULL; printf("Deleted Node is:n");
  • 42. 32 Department of CS&E, BGSCET display(cur); free(cur); return; } void displayList() { NODE *r; r=first; printf("USNtNametBrhtSemtPhonen"); if(r==NULL) return; while(r!=NULL) { display(r); r=r->next; } printf("n"); } STUD input() { STUD s; printf("Enter USN: "); scanf("%s",s.usn); printf("Enter Name : "); scanf("%s",s.name); printf("Enter Branch: "); scanf("%s",s.branch); printf("Enter Sem:"); scanf("%d",&s.sem); printf("Enter Phone no : "); scanf("%llu",&s.phno); return s; } int count()
  • 43. 33 Department of CS&E, BGSCET { NODE *n; int c=0; n=first; while(n!=NULL) { n=n->next; c++; } return c; } int main() { STUD s; int i,ch, n; first=NULL; while(1) { printf("nList Operationsn"); printf("===============n"); printf("1.Create List of n students by using front Insertn"); printf("2.Display the status and count the nodesn"); printf("3.Perform Insertion and Deletion at End of SLLn"); printf("4.Perform Insertion and Deletion at Front of SLLn"); printf("5.Exitn"); printf("Enter your choice : "); scanf("%d",&i); switch(i) { case 1 : printf("Enter the number of studentsn"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("nEnter the details of student %dn",i); s=input();
  • 44. 34 Department of CS&E, BGSCET addfront(s); } break; case 2 : if(first==NULL) { printf("List is Emptyn"); } else printf(" Node Count=%dt & Elements in the list are : n", count()); displayList(); } break; case 3 : printf(" 1. Insert at End and 2 Delete From End="); scanf("%d",&ch); if(ch==1) { s=input(); addrear(s); } else if(ch==2) deleterear(); else printf(" Sorry wrong operationn"); break; case 4 : printf(" 1. Insert at Front and 2.Delete From Front="); scanf("%d",&ch); if(ch==1) { s=input(); addfront(s); } else if(ch==2) deletefront(); else printf(" Sorry wrong operationn"); case 5 :exit (0); default : printf("Invalid optionn"); } } return 0; }
  • 45. 35 Department of CS&E, BGSCET Output List Operations =============== 1.Create List of n students by using front Insert 2.Display the status and count the nodes 3.Perform Insertion and Deletion at End of SLL 4.Perform Insertion and Deletion at Front of SLL 5.Exit Enter your choice : 1 Enter the number of students 2 Enter the details of student 1 Enter USN: 1mp22is001 Enter Name : aishwarya Enter Branch: ise Enter Sem:3 Enter Phone no : 8765432192 Enter the details of student 2 Enter USN: 1mp22cs002 Enter Name : abhishek Enter Branch: cse Enter Sem:3 Enter Phone no : 9876543213 List Operations =============== 1.Create List of n students by using front Insert 2.Display the status and count the nodes 3.Perform Insertion and Deletion at End of SLL 4.Perform Insertion and Deletion at Front of SLL 5.Exit Enter your choice : 3 1. Insert at End and 2 Delete From End=1 Enter USN: 1mp22ec003 Enter Name : asha Enter Branch: ec
  • 46. 36 Department of CS&E, BGSCET Enter Sem:3 Enter Phone no : 8976543218 List Operations =============== 1.Create List of n students by using front Insert 2.Display the status and count the nodes 3.Perform Insertion and Deletion at End of SLL 4.Perform Insertion and Deletion at Front of SLL 5.Exit Enter your choice : 2 Node Count=3 & Elements in the list are : USN Name Brh Sem Phone 1mp22cs002 abhishek cse 3 9876543213 1mp22is001 aishwarya ise 3 8765432192 1mp22ec003 asha ec 3 8976543218 List Operations =============== 1.Create List of n students by using front Insert 2.Display the status and count the nodes 3.Perform Insertion and Deletion at End of SLL 4.Perform Insertion and Deletion at Front of SLL 5.Exit Enter your choice : 2 Node Count=3 & Elements in the list are : USN Name Brh Sem Phone 1mp22cs002 abhishek cse 3 9876543213 1mp22is001 aishwarya ise 3 8765432192 1mp22ec003 asha ec 3 8976543218 List Operations =============== 1.Create List of n students by using front Insert 2.Display the status and count the nodes 3.Perform Insertion and Deletion at End of SLL 4.Perform Insertion and Deletion at Front of SLL
  • 47. 37 Department of CS&E, BGSCET 5.Exit Enter your choice : 4 1. Insert at Front and 2.Delete From Front=2 Deleted Node is: 1mp22cs002 abhishek cse 3 9876543213
  • 48. 38 Department of CS&E, BGSCET Program 8: Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo a. Create a DLL of N Employees Data by using end insertion. b. Display the status of DLL and count the number of nodes in it. c. Perform Insertion and Deletion at End of DLL d. Perform Insertion and Deletion at Front of DLL e. Demonstrate how this DLL can be used as Double Ended Queue. f. Exit #include<stdio.h> #include<stdlib.h> #include<string.h> struct employee { char ssn[11]; char name[21]; char dept[15]; char design[15]; int salary; unsigned long long phno; }; typedef struct employee EMP; struct node { char ssn[11]; char name[21]; char dept[15]; char design[15]; int salary; unsigned long long phno; struct node *next; struct node *prev; }; typedef struct node NODE; NODE *first; NODE* copyNode(EMP e) { NODE * temp; temp= (NODE *)malloc(sizeof(NODE)); if(temp==NULL)
  • 49. 39 Department of CS&E, BGSCET { printf("Memory cannot be allocatedn"); } else { strcpy(temp->ssn,e.ssn); strcpy(temp->name, e.name); strcpy(temp->dept, e.dept); strcpy(temp->design, e.design); temp->salary=e.salary; temp->phno=e.phno; temp->next=NULL; temp->prev=NULL; return temp; } } void addrear(EMP e) { NODE *temp,*cur, *prev; temp=copyNode(e) ; if(first==NULL) { first=temp; return; } cur=first; prev=NULL; while(cur->next != NULL) { prev=cur; cur=cur->next; } cur->next =temp; temp->prev=prev; return ; } void addfront(EMP e) { NODE *temp;
  • 50. 40 Department of CS&E, BGSCET temp=copyNode(e); if (first== NULL) { first=temp; } else { temp->next=first; first->prev=temp; first=temp; } return ; } void display(NODE *r) { printf("%st", r->ssn); printf("%st", r->name); printf("%st", r->dept); printf("%st",r->design); printf("%dt",r->salary); printf("%llun", r->phno); } void deletefront() { NODE *temp; int num; temp=first; if(first==NULL) { printf(" List is Empty n"); return ; } if(first->next==NULL) first=NULL; else { first=first->next; first->prev=NULL; }
  • 51. 41 Department of CS&E, BGSCET printf("SSNtNametDepttDesignationtSalarytPhonen"); display(temp); free(temp); return ; } void deleterear() { NODE *cur, *prev; cur=first; prev=NULL; if(first==NULL) { printf(" List is Empty n"); return ; } if(first->next==NULL) { first=NULL; } else { while(cur->next!=NULL) { prev=cur; cur=cur->next; } prev->next=NULL; } printf("SSNtNametDepttDesignationtSalarytPhonen"); display(cur); free(cur); return; } void displayList() { NODE *r; r=first; if(r==NULL) { return;
  • 52. 42 Department of CS&E, BGSCET } printf("SSNt Namet Deptt Designationt salarytPhonen"); while(r!=NULL) { display(r); r=r->next; } printf("n"); } int count() { NODE *n; int c=0; n=first; while(n!=NULL) { n=n->next; c++; } return c; } EMP input() { EMP e; printf("Enter SSN: "); scanf("%s",e.ssn); printf("Enter Name: "); scanf("%s",e.name); printf("Enter dept: "); scanf("%s",e.dept); printf("Enter Designation :"); scanf("%s",e.design); printf("Enter Salary:"); scanf("%d",&e.salary); printf("Enter Phone no : "); scanf("%llu",&e.phno); return e; } int main() {
  • 53. 43 Department of CS&E, BGSCET EMP e; int i, ch, n; first=NULL; while(1) { printf("nList Operationsn"); printf("===============n"); printf("1.Create a DLL of N Employees Data by using end insertionn"); printf("2.Display the status of DLL and count the number of nodes in itn"); printf("3.Perform Insertion and Deletion at End of DLLn"); printf("4.Perform Insertion and Deletion at Front of DLLn"); printf("5.Demonstration of this DLL as Double Ended Queuen"); printf("6.Exitn"); printf("Enter your choice : "); scanf("%d",&i); switch(i) { case 1 : printf("Enter the number of Employeesn"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("nEnter the details of Employee %dn",i); e=input(); addrear(e); } break; case 2 : if(first==NULL) { printf("List is Emptyn"); } else { printf(" Node Count=%dt & Elements in the list are : n", count()); displayList(); } break;
  • 54. 44 Department of CS&E, BGSCET case 3 : printf(" 1. Insert at End and 2 Delete From End="); scanf("%d",&ch); if(ch==1) { e=input(); addrear(e); } else if(ch==2) deleterear(); else printf(" Sorry wrong operationn"); break; case 4 : printf(" 1. Insert at Front and 2 Delete From Front="); scanf("%d",&ch); if(ch==1) { e=input(); addfront(e); } else if(ch==2) deletefront(); else printf(" Sorry wrong operationn"); break; case 5: printf("This DLL can be used as Double Ended Queue by inserting and deleting from both ends n"); break; case 6 : return 0; default : printf("Invalid optionn"); } } return 0; }
  • 55. 45 Department of CS&E, BGSCET Output: List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 1 Enter the number of Employees 2 Enter the details of Employee 1 Enter SSN: 111 Enter Name: Ram Enter dept: Sales Enter Designation :Manager Enter Salary:50000 Enter Phone no : 9141000000 Enter the details of Employee 2 Enter SSN: 222 Enter Name: Sham Enter dept: Design Enter Designation :Manager Enter Salary:60000 Enter Phone no : 9876543210 List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 2 Node Count=2 & Elements in the list are :
  • 56. 46 Department of CS&E, BGSCET SSN Name Dept Designation salary Phone 111 Ram Sales Manager 50000 9141000000 222 Sham Design Manager 60000 9876543210 List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 3 1. Insert at End and 2 Delete From End=1 Enter SSN: 333 Enter Name: Ravi Enter dept: Finance Enter Designation :Manager Enter Salary:65000 Enter Phone no : 9876500000 List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 2 Node Count=3 & Elements in the list are : SSN Name Dept Designation salary Phone 111 Ram Sales Manager 50000 9141000000 222 Sham Design Manager 60000 9876543210 333 Ravi Finance Manager 65000 9876500000 List Operations ===============
  • 57. 47 Department of CS&E, BGSCET 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 4 1. Insert at Front and 2 Delete From Front=2 SSN Name Dept Designation Salary Phone 111 Ram Sales Manager 50000 9141000000 List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 2 Node Count=2 & Elements in the list are : SSN Name Dept Designation salary Phone 222 Sham Design Manager 60000 9876543210 333 Ravi Finance Manager 65000 9876500000 List Operations =============== 1.Create a DLL of N Employees Data by using end insertion 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 5 This DLL can be used as Double Ended Queue by inserting and deleting from both ends List Operations =============== 1.Create a DLL of N Employees Data by using end insertion
  • 58. 48 Department of CS&E, BGSCET 2.Display the status of DLL and count the number of nodes in it 3.Perform Insertion and Deletion at End of DLL 4.Perform Insertion and Deletion at Front of DLL 5.Demonstration of this DLL as Double Ended Queue 6.Exit Enter your choice : 6
  • 59. 49 Department of CS&E, BGSCET Program 9: Develop a Program in C for the following operations on Singly Circular Linked List (SCLL) with header nodes a. Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3 b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in POLYSUM(x,y,z). Support the program with appropriate functions for each of the above operations. #include<stdio.h> #include<stdlib.h> #include<math.h> int coef,px,py,pz, x,y,z,i; int val; struct node { int coef,px, py,pz; struct node *next; }; typedef struct node NODE; NODE *first; void insert(int coef,int px, int py, int pz) { NODE *temp,*cur; temp= (NODE *)malloc(sizeof(NODE)); temp->coef=coef; temp->px=px; temp->py=py; temp->pz=pz; if(first==NULL) { temp->next=temp; first=temp; return; } if(first->next==first) { first->next=temp; temp->next=first;
  • 60. 50 Department of CS&E, BGSCET } cur=first; while(cur->next!=first) { cur=cur->next; } cur->next=temp; temp->next=first; return; } void display() { NODE *cur; if(first==NULL) { printf("List is emptyn"); return; } cur=first; while(cur->next!=first) { printf("%d ",cur->coef); printf(" x^%d",cur->px); printf(" y^%d",cur->py); printf(" z^%d + ",cur->pz); cur=cur->next; } printf("%d ",cur->coef); printf(" x^%d",cur->px); printf(" y^%d",cur->py); printf(" z^%dn",cur->pz); return; } int evaluate(int x, int y, int z) { NODE *cur; int v,s=0, v1,v2,v3; if(first==NULL) {
  • 61. 51 Department of CS&E, BGSCET printf("List is emptyn");return 0; } cur=first; while(cur->next!=first) { v=cur->coef*pow(x, cur->px)*pow(y, cur->py)*pow(z,cur->pz); s=s+v; cur=cur->next; } v=cur->coef*pow(x, cur->px)*pow(y, cur->py)*pow(z,cur->pz); s=s+v; return s; } int main() { int coef,px,py,pz, x,y,z,i; int val; first=NULL; while(1) { printf("1. Insert polynomial at endn"); printf("2. Displayn"); printf("3. Evaluaten"); printf("4. Exitn"); printf("Enter Choice= t"); scanf("%d",&i); switch(i) { case 1 : printf("Enter Coefficient= t"); scanf("%d",&coef); printf("Enter powers of x y z values= t"); scanf("%d%d%d",&px, &py,&pz); insert(coef,px,py,pz); break; case 2 : display(); break; case 3 : printf("n Enter x y & z values for evaluation: t"); scanf("%d%d%d",&x,&y,&z);
  • 62. 52 Department of CS&E, BGSCET val=evaluate(x,y,z); printf("nValue=%dn",val); break; case 4 : return 0; default : printf(" Wrong choice. Enter 1,2 3n"); break; } } } Output: 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 1 Enter Coefficient= 4 Enter powers of x y z values= 3 3 2 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 1 Enter Coefficient= 5 Enter powers of x y z values= 3 2 2 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 1 Enter Coefficient= 3 Enter powers of x y z values= 2 2 2 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 1 Enter Coefficient= 6 Enter powers of x y z values= 1 1 1
  • 63. 53 Department of CS&E, BGSCET 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 2 4 x^3 y^3 z^2 + 5 x^3 y^2 z^2 + 3 x^2 y^2 z^2 + 6 x^1 y^1 z^1 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 3 Enter x y & z values for evaluation: 3 2 1 Value=1548 1. Insert polynomial at end 2. Display 3. Evaluate 4. Exit Enter Choice= 4 Program 9B #include<stdio.h> #include<stdlib.h> #include<math.h> struct node //Defining Polynomial fields { int coef, px, py, pz,flag; struct node *link; }; typedef struct node * NODE; NODE create_list(NODE head) //For creating poly1 & poly2 { int i,n,cf,px,py,pz; printf("Enter the number of terms : "); scanf("%d",&n);
  • 64. 54 Department of CS&E, BGSCET for(i=1;i<=n;i++) { printf("Enter the Co-ef, px, py, pz : "); scanf("%d %d %d %d",&cf,&px,&py,&pz); insert(head,cf,px,py,pz); } return head; }/*End of create_list()*/ insert(NODE head,int cof,int x,int y, int z) //inserting term to poly { NODE cur,tmp; tmp= (NODE)malloc(sizeof(struct node)); //Allocates memory int cf,px,py,pz; cur=head->link; tmp->coef=cof; tmp->px=x; tmp->py=y; tmp->pz=z; tmp->flag=0; while(cur->link!=head) //Identifying last node cur=cur->link; cur->link=tmp; tmp->link=head; } NODE add_poly(NODE h1,NODE h2,NODE h3) { NODE cur1,cur2,scf; cur1=h1->link; cur2=h2->link; while(cur1 != h1) //Till end of poly1 { if(cur2 == h2) cur2=h2->link; while(cur2 != h2) //Till end of poly2 { if(cur1->px == cur2->px && cur1->py == cur2->py && cur1->pz == cur2->pz) { //Add & insert if co-ef's of both poly is equal scf = cur1->coef + cur2->coef; insert(h3,scf,cur1->px,cur1->py,cur1->pz); cur2->flag=1;
  • 65. 55 Department of CS&E, BGSCET cur2=h2->link; break; } cur2=cur2->link; } if(cur1 == h1) break; if(cur2 == h2) //If co-ef of poly1 is not matched, insert it to poly3 insert(h3,cur1->coef,cur1->px,cur1->py,cur1->pz); cur1=cur1->link; } cur2=h2->link; while(cur2 != h2) //remaining poly2 nodes inserted to poly3 { if(cur2->flag==0) insert(h3,cur2->coef,cur2->px,cur2->py,cur2->pz); cur2=cur2->link; } return h3; } void display(NODE head) { NODE cur; if(head->link==head) //if poly is empty { printf("List is emptyn"); return; } cur=head->link; while(cur != head) //display all terms till end { if(cur->coef > 0) printf(" +%dx^%dy^%dz^%d ",cur->coef,cur->px,cur->py,cur->pz); else if (cur->coef < 0) printf(" %dx^%dy^%dz^%d ",cur->coef,cur->px,cur->py,cur->pz); cur=cur->link; } printf("n"); }/*End of display() */
  • 66. 56 Department of CS&E, BGSCET void main() { int choice,data,item,pos; NODE head1,head2,head3; head1=(NODE)malloc(sizeof(struct node)); head1->link=head1; //poly1 head2=(NODE)malloc(sizeof(struct node)); head2->link=head2; //poly2 head3=(NODE)malloc(sizeof(struct node)); head3->link=head3; //poly3 printf("n1.Create Polynomial 1n"); head1=create_list(head1); printf("n2.Create Polynomial 2n"); head2=create_list(head2); printf("nPolynomial 1 is :"); display(head1); printf("nPolynomial 2 is :"); display(head2); head3=add_poly(head1,head2,head3); //Add both polynomials printf("nAddition of two Polynomial is :"); display(head3); } Output: 1.Create Polynomial 1 Enter the number of terms : 4 Enter the Co-ef, px, py, pz : 5 3 3 3 Enter the Co-ef, px, py, pz : 6 3 3 2 Enter the Co-ef, px, py, pz : 8 2 2 2
  • 67. 57 Department of CS&E, BGSCET Enter the Co-ef, px, py, pz : 9 1 0 1 2.Create Polynomial 2 Enter the number of terms : 4 Enter the Co-ef, px, py, pz : 6 3 3 3 Enter the Co-ef, px, py, pz : 5 2 2 2 Enter the Co-ef, px, py, pz : 8 2 1 2 Enter the Co-ef, px, py, pz : 9 1 1 0 Polynomial 1 is : +5x^3y^3z^3 +6x^3y^3z^2 +8x^2y^2z^2 +9x^1y^0z^1 Polynomial 2 is : +6x^3y^3z^3 +5x^2y^2z^2 +8x^2y^1z^2 +9x^1y^1z^0 Addition of two Polynomial is : +6x^3y^3z^2 +9x^1y^0z^1 +6x^3y^3z^3 +5x^2y^2z^2 +8x^2y^1z^2 +9x^1y^1z^0
  • 68. 58 Department of CS&E, BGSCET Program 10: Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers . a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2 b. Traverse the BST in Inorder, Preorder and Post Order c. Search the BST for a given element (KEY) and report the appropriate message d. Exit #include<stdio.h> #include<conio.h> #include<stdlib.h> int choice,data,key; struct node { int info; struct node *lchild,*rchild; }; typedef struct node *NODE; int main() { NODE root=NULL; NODE CREATE(NODE,int); void INORDER(NODE),POSTORDER(NODE),PREORDER(NODE); NODE SEARCH_NODE(NODE,int); while(1) { printf("n1:CREATEn2:TREE TRAVERSALn3.SEARCHn4.EXIT"); printf("nEnter your choicen"); scanf("%d",&choice); switch(choice) { case 1: printf("nEnter data to be insertedn"); scanf("%d",&data); root=CREATE(root,data); break; case 2: if(root==NULL) printf("nEMPTY TREEn"); else
  • 69. 59 Department of CS&E, BGSCET { printf("nThe Inorder display : "); INORDER(root); printf("nThe Preorder display : "); PREORDER(root); printf("nThe Postorder display : "); POSTORDER(root); } break; case 3: printf("nenter the key to search:n"); scanf("%d",&key); SEARCH_NODE(root,key); break; case 4: exit(0); } } } NODE CREATE(NODE root,int data) { NODE newnode,x,parent; newnode=(NODE)malloc(sizeof(struct node)); newnode->lchild=newnode->rchild=NULL; newnode->info=data; if(root==NULL) root=newnode; else { x=root; while(x!=NULL) { parent=x; if(x->info<data) x=x->rchild; else if(x->info>data) x=x->lchild; else { printf("nNode is already present in the treen"); return(root); }
  • 70. 60 Department of CS&E, BGSCET } if(parent->info<data) parent->rchild=newnode; else parent->lchild=newnode; } return(root); } void INORDER(NODE root) { if(root!=NULL) { INORDER(root->lchild); printf("%d ",root->info); INORDER(root->rchild); } } void PREORDER(NODE root) { if(root!=NULL) { printf("%d ",root->info); PREORDER(root->lchild); PREORDER(root->rchild); } } void POSTORDER(NODE root) { if(root!=NULL) { POSTORDER(root->lchild); POSTORDER(root->rchild); printf("%d ",root->info); } } NODE SEARCH_NODE(NODE root, int key) {
  • 71. 61 Department of CS&E, BGSCET NODE cur,q,parent,successor; if(root==NULL) { printf("nTree is emptyn"); return root; } parent=NULL,cur=root; while(cur!=NULL) { if(key==cur->info) break; parent=cur; cur= (key<cur->info)?cur->lchild:cur->rchild; } if(cur==NULL) { printf("nData is not foundn"); return root; } printf("nData %d is foundn",key); } Output: 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 2 EMPTY TREE
  • 72. 62 Department of CS&E, BGSCET 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 6 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 9 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 5 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted
  • 73. 63 Department of CS&E, BGSCET 2 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 8 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 15 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 24 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1
  • 74. 64 Department of CS&E, BGSCET Enter data to be inserted 14 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 7 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 8 Node is already present in the tree 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 1 Enter data to be inserted 5 Node is already present in the tree 1:CREATE 2:TREE TRAVERSAL
  • 75. 65 Department of CS&E, BGSCET 3.SEARCH 4.EXIT Enter your choice 2 The Inorder display : 2 5 6 7 8 9 14 15 24 The Preorder display : 6 5 2 9 8 7 15 14 24 The Postorder display : 2 5 7 8 14 24 15 9 6 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 3 enter the key to search: 14 Data 14 is found 1:CREATE 2:TREE TRAVERSAL 3.SEARCH 4.EXIT Enter your choice 3 enter the key to search: 4 Data is not found
  • 76. 66 Department of CS&E, BGSCET Program 11: Design, develop and implement a Program in C for the following operations on Graph (G) of Cities Create a Graph of N cities using Adjacency Matrix. Print all the nodes reachable from a given starting node in a digraph using BFS method #include<stdio.h> #include<stdlib.h> int n,a[10][10],i,j,source,s[10],choice,count; void bfs(int n,int a[10][10],int source,int s[]) //BFS Algorithm { int q[10],u; int front=1,rear=1; s[source]=1; q[rear]=source; while(front<=rear) { u=q[front]; front=front+1; for(i=1;i<=n;i++) if(a[u][i]==1 && s[i]==0) { rear=rear+1; q[rear]=i; s[i]=1; } } } int main() { printf("Enter the number of nodes : "); scanf("%d",&n); printf("n Enter the adjacency matrixn"); for(i=1;i<=n;i++) //Provide matrix of 0’s and 1’s for(j=1;j<=n;j++) scanf("%d",&a[i][j]);
  • 77. 67 Department of CS&E, BGSCET while(1) { printf("nEnter your choicen"); printf("1.BFSn 2.Exitn"); scanf("%d",&choice); switch(choice) { case 1: printf("n Enter the source :"); scanf("%d",&source); //Provide source for BFS for(i=1;i<=n;i++) s[i]=0; bfs(n,a,source,s); for(i=1;i<=n;i++) { if(s[i]==0) printf("n The node %d is not reachable",i); else printf("n The node %d is reachable",i); } break; case 2: exit(0); } } } Output: Enter the number of nodes : 5 Enter the adjacency matrix
  • 78. 68 Department of CS&E, BGSCET 0 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 1 0 Enter your choice 1.BFS 2.Exit 1 Enter the source :5 The node 1 is reachable The node 2 is reachable The node 3 is reachable The node 4 is reachable The node 5 is reachable Enter your choice 1.BFS 2.Exit 1 Enter the source :1 The node 1 is reachable
  • 79. 69 Department of CS&E, BGSCET The node 2 is reachable The node 3 is reachable The node 4 is reachable The node 5 is not reachable Enter your choice 1.BFS 2.Exit 2
  • 80. 70 Department of CS&E, BGSCET PROGRAM 12: Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory locations with L as the set of memory addresses (2-digit) of locations in HT. Let the keys in K and addresses in L are Integers. Develop a Program in C that uses Hash function H: K →L as H(K)=K mod m (remainder method), and implement hashing technique to map a given key K to the address space L. Resolve the collision (if any) using linear probing. #include <stdio.h> #include <stdlib.h> #define MAX 5 #define mod(x) x%MAX void linear_prob(int a[],int num,int key) { if(a[key]==-1) a[key]=num; else { printf("nCollision detected!!"); int i; for(i=mod(key+1);i!=key;i=mod(++i)) if(a[i]==-1) break; if(i!=key) { printf("nCollision avoided successfullyn"); a[i]=num; } else printf("nHash table is fulln"); } } void display(int a[]) { short ch,i; printf("n1.Filtered displayn2.Display allnEnter choice:"); scanf("%hd",&ch);
  • 81. 71 Department of CS&E, BGSCET printf("nHash table is :n"); for(i=0;i<MAX;i++) if(a[i]>0||ch-1) printf("%d %dn",i,a[i]); } int main() { int a[MAX],num,i; printf("nCollision handling by linear probing"); for(i=0;i<MAX;a[i++]=-1); do { printf("nEnter the data:"); scanf("%4d",&num); linear_prob(a,num,mod(num)); printf("Do u wish to continue(1/0):"); scanf("%d",&i); }while(i); display(a); return 0; } Output: Collision handling by linear probing Enter the data:5 Do u wish to continue(1/0):1 Enter the data:4 Do u wish to continue(1/0):1 Enter the data:3 Do u wish to continue(1/0):0 1.Filtered display 2.Display all Enter choice:1 Hash table is : 0 5 3 3
  • 82. 72 Department of CS&E, BGSCET Appendix A SAMPLE PROGRAMS ON DATA STRUCTURES Program 1 Write a C program to implement pointer operations. // Program to implement pointer operations #include<stdio.h> #include<conio.h > void main() { int i_num =3, *i_ptr=&i_num; clrscr(); printf("nAddress of i_num=0X%x",&i_num); printf("nAddress of i_num=0X%x",i_ptr); printf("nAddress of i_ptr=0X%x",&i_ptr); printf("nAddressof i_num through pointer=0X%x",i_ptr); printf("nValue of i_num=%d",i_num); printf("nValue of i_num through pointer symbols=%d",*(&i_num)); printf("nValue of I through pointer=%d",*i_ptr); getch(); } Program2 Write a C program to exchange two values using pointers. // Program to exchange two values #include<stdio.h> #include<conio.h > void main()
  • 83. 73 Department of CS&E, BGSCET { int i_num1, i_num2; void swap(int*, int*); clrscr(); printf("Enter 2 integersn"); scanf("%d%d", &i_num1, &i_num2); printf("Values before swapping are %d and %dnn",i_num1,i_num2); swap(&i_num1,&i_num2); printf("Values after swapping are %d and %dnn",i_num1,i_num2); getch(); } void swap(int *x,int *y) { int temp =*x; *x=*y; *y=temp; } Program 3 Write a program to create a structure named student with variables book ID, name and price. Create a variable of type structure, initialize the details and print them on the screen.
  • 84. 74 Department of CS&E, BGSCET // Program to implement structure #include <stdio.h> #include <conio.h> struct book { int i_book _id; char *c_na me; float f_price ; } b; void main() { clrscr(); b.i_book_id =1; b.c_name = "Fundamentals of Data Structure"; b.f_price = 390.5; printf("Book Id is : %d n", b.i_book_id); printf("Name is : %s n", b.c_name); printf("Price is : %f n", b.f_price); getch(); }
  • 85. 75 Department of CS&E, BGSCET APPENDIX B: VIVA QUESTIONS WITH ANSWERS 1. What is data structure? A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. 2. List out the areas in which data structures are applied extensively? · Compiler Design · Operating System · Database Management System · Statistical analysis package · Numerical Analysis · Graphics · Artificial Intelligence · Simulation 3. What are the major data structures used in the following areas: RDBMS, Network data model and Hierarchical data model? · RDBMS = Array (i.e. Array of structures) · Network data model = Graph · Hierarchical data model = Trees 4. What is the Minimum number of queues needed to implement the priority queue? Two. One queue is used for actual storing of data and another for storing priorities. 5. What is the data structures used to perform recursion? Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. 6. In tree construction which is the suitable efficient data structure? (Array, Linked list, Stack, Queue) Linked list is the suitable efficient data structure.
  • 86. 76 Department of CS&E, BGSCET 7. What is the significant difference between ARRAY and STACK? Stack uses LIFO. Thus the item that is certainly first entered would be the last removed. In array the items could be entered or removed in any order. Basically each and every member access is done making use of index and no strict order is to be followed here to remove a particular element. Array could be multi-dimensional or one dimensional but stack really should be one-dimensional. Size of array is fixed, while stack may be grow or shrink. We can say stack is actually dynamic data structure. 8. Explain whether Linked List is actually linear or Non-linear data structure? Link list is definitely obviously linear data structure simply because each and every element (NODE) acquiring specific place and as well each and every component has got its unique successor in addition to predecessor. 9. What is the difference between a Stack and a Queue? Stack follows LIFO (Last In First Out) method of accessing the members. Queue follows FIFO (First In First Out) method of accessing the members. 10. What is a one way chain or singly linked linear list? Singly linked list is a collection of nodes. Each node has element and address of the next element. With that address only forward traversal is possible i.e. single link 11. How can a node be inserted in the middle of a linked list? By repointing the previous and the next elements of existing nodes to the new node. 11. What is the heap? The heap is where malloc(), calloc(), and realloc() get memory. 12. Which data structure is needed to convert infix notations to post fix notations? Stack 13. List out few of the applications that make use of Multilinked Structures? · Sparse matrix. · Index generation. 14. In tree construction which is the suitable efficient data structure? Linked List
  • 87. 77 Department of CS&E, BGSCET 15. What is the evaluation order according to which an infix expression is converted to postfix expression? The evaluation order is: · Brackets or Parenthesis, · Exponentiation, · Multiplication or division, · Addition or subtraction. 16. Give the advantages of using post fix notations over infix notations? An infix expression is evaluated keeping in mind the precedence of operators. An infix expression is difficult for the machine to know and keep track of precedence of operators. A postfix expression itself takes care of the precedence of operators as the placement of operators. Thus, for the machine, it is easier to carry out a postfix expression than an infix expression. 17. List out few of the Application of tree data-structure? The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis. 18. In RDBMS, what is the efficient data structure used in the internal storage representation? B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes. 19. Why do we Use a Multidimensional Array? A multidimensional array can be useful to organize subgroups of data within an array. 20. Run Time Memory Allocation is known as? Allocating memory at runtime is called a dynamically allocating memory. In this, you dynamically allocate memory by using the new operator when declaring the array, for example: int grades [] = new int [10];