0% found this document useful (0 votes)
14 views25 pages

DSA Lab Manual 1 2 3

The document is a laboratory manual for the Data Structures Laboratory (BCSL305) for the academic year 2023-24 at East Point College of Engineering and Technology. It outlines the program outcomes, educational objectives, course learning objectives, and a list of practical programming assignments to be completed by students, focusing on various data structures and their applications. Additionally, it provides information on the institute's vision and mission, as well as suggested learning resources and guidelines for practical examinations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views25 pages

DSA Lab Manual 1 2 3

The document is a laboratory manual for the Data Structures Laboratory (BCSL305) for the academic year 2023-24 at East Point College of Engineering and Technology. It outlines the program outcomes, educational objectives, course learning objectives, and a list of practical programming assignments to be completed by students, focusing on various data structures and their applications. Additionally, it provides information on the institute's vision and mission, as well as suggested learning resources and guidelines for practical examinations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Department of CSE-(IoT & CSBT)

‘Jnana Prabha’, Virgo Nagar Post, Bengaluru-560049

Academic Year: 2023-24

LABORATORY MANUAL

SEMESTER : III

SUBJECT : Data Structures Laboratory

SUBCODE : BCSL305

NAME: ____________________________________________________________

USN: _____________________________________________________________

SECTION: __________________________________________________________

BATCH: ___________________________________________________________
DATA STRUCTURES LABORATORY (BCSL305) 2023-2024

PROGRAM OUTCOMES
Engineering Graduates will able to:

Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.

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.

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.

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.

Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding
of the limitations.

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.

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.

Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

Individual and Team Work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.

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.

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.

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.
DATA STRUCTURES LABORATORY (BCSL305) 2023-2024

INSTITUTE VISION AND MISSION


VISION

The East Point College of Engineering and Technology aspires to be a globally acclaimed
institution, recognized for excellence in engineering education, applied research and nurturing
students for holistic development.

MISSION

M1: To create engineering graduates through quality education and to nurture innovation,
creativity and excellence in teaching, learning and research
M2: To serve the technical, scientific, economic and societal developmental needs of our
communities
M3: To induce integrity, teamwork, critical thinking, personality development and ethics in
students and to lay the foundation for lifelong learning
DATA STRUCTURES LABORATORY (BCSL305) 2023-2024

Department of CSE-(IoT & CSBT)

DEPARTMENT VISION AND MISSION


VISION

To be the foremost innovator and leader in the field of IoT and Cyber security, driving the
evolution of secure and connected technologies, ensuring the trust and safety of digital
ecosystems worldwide.

MISSION
M1: We are dedicated to advancing digital trust by pioneering cutting-edge solutions that
secure IoT devices, networks, and data, guaranteeing the reliability and privacy of the
connected world.

M2: Our mission is to continuously innovate and develop robust cyber security technologies
that proactively anticipate and counter emerging threats, fostering a secure environment for IoT
applications.

M3: We are committed to educating and empowering businesses, individuals, and communities
through extensive training and awareness programs, equipping them with the knowledge to
defend against cyber threats.
DATA STRUCTURES LABORATORY (BCSL305) 2023-2024

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO 1: Graduates will have successful careers in IoT and Cybersecurity or related fields,
demonstrating expertise and leadership in securing and managing interconnected systems.

PEO 2: Graduates will engage in lifelong learning and professional development, staying
current with evolving technologies and security threats to adapt to changing industry demands.

PEO 3: Graduates will possess the skills to analyze and solve complex IoT and cybersecurity
challenges, applying critical thinking, ethical decision-making, and innovative approaches.

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO 1: Graduates will be proficient in understanding, configuring, and securing IoT devices,
networks, and platforms, including familiarity with IoT protocols and technologies.

PSO 2: Graduates will have expertise in securing IoT devices, including hardware security,
firmware integrity, and encryption of data at rest and in transit.

PSO 3: Graduates will possess the skills to conduct digital forensics investigations in IoT
environments to trace and analyze security incidents.

COURSE LEARNING OBJECTIVES


CLO1: Dynamic memory management.
CLO2: Linear data structures and their applications such as stacks, queues and lists
CLO3: Non-Linear data structures and their applications such as trees and graphs.

COURSE OUTCOMES
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.
DATA STRUCTURES AND APPLICATIONS
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2023-2024)
SEMESTER – III
Course Code BCSL305 CIE Marks 50
Number of Lecture Hours/Week 0:0:2 SEE Marks 50
Total Number of Lecture Hours 28
CREDITS – 01
Course Learning Objectives:

This laboratory course enables students to get practical experience in design, develop,
implement, analyze and evaluation/testing of

CLO 1. Dynamic memory management


CLO 2. Linear data structures and their applications such as stacks, queues and lists
CLO 3. Non-Linear data structures and their applications such as trees and graphs

Laboratory Component Description

Prerequisite

 Students should be familiarized about C Programming Concepts


 Familiar with Linux.

Sl.No List of problems for which student should develop program and execute in the
Laboratory
1 Aim: Demonstrate Creation and Display of array of structures
Program: 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.
2 Aim: Demonstrate the string Operations
Program: 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.
3 Aim: Implement stack operations
Program: 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
4 Aim: Implement the applications of stack
Program: 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
5 Aim: Implement the applications of stack
Program: Design, Develop and Implement a Program in C for the following Stack
Application
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks

6 Aim: Demonstrate the implementation of Circular Queue


Program: 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 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
7 Aim: Implement SLL Single linked list (SLL) of N Students Data
Program: 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
8 Aim: Implement stack and queue using doubly linked list(DLL)
Program: 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
9 Aim: Construct Circular Single Linked List
Program: 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) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5 z-2xyz 3
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
10 Aim: Construct Binary Search Tree
Program: 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

11 Aim: Implement Graph Traversal Methods


Program: Design, Develop and implement 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 diagraph
using DFS/BFS Method

12 Aim: Demonstrate collision resolving


Program: Design and develop a program in C that uses Hash Function H:K->L as H(K)=K
mod m(reminder method) and implement hashing technique to map a given key K to the
address space L. Resolve the collision (if any) using linear probing.

Course Outcomes
At the end of the course the student will be able to:

CO 1. Identify different data structures and their applications.


CO 2. Apply stack and queues in solving problems.
CO 3. Demonstrate applications of linked list.
CO 4. Explore the applications of trees and graphs to model and solve the real-world problem.
CO 5. Make use of Hashing techniques and resolve collisions during mapping of key value pairs

Suggested Learning Resources:


Textbooks:
1. Ellis Horowitz and Sartaj Sahni, Fundamentals of Data Structures in C, 2nd Ed, Universities Press,
2014.

Reference Books:
1. Seymour Lipschutz, Data Structures Schaum's Outlines, Revised 1st Ed, McGraw Hill, 2014.
2. Reema Thareja, Data Structures using C, 3rd Ed, Oxford press, 2012
3. Gilberg and Forouzan, Data Structures: A Pseudo-code approach with C, 2nd Ed, Cengage
Learning,2014.
4. Jean-Paul Tremblay & Paul G. Sorenson, An Introduction to Data Structures with Applications,2nd
Ed, McGraw Hill, 2013
5. A M Tenenbaum, Data Structures using C, PHI, 1989
6. Robert Kruse, Data Structures and Program Design in C, 2nd Ed, PHI, 1996.

Weblinks and Video Lectures (e-Resources):

● http://elearning.vtu.ac.in/econtent/courses/video/CSE/06CS35.html
● https://nptel.ac.in/courses/106/105/106105171/
● http://www.nptelvideos.in/2012/11/data-structures-and-algorithms.html
● https://www.youtube.com/watch?v=3Xo6P_V-qns&t=201s
● https://ds2-iiith.vlabs.ac.in/exp/selection-sort/index.html
● https://nptel.ac.in/courses/106/102/106102064/
● https://ds1-iiith.vlabs.ac.in/exp/stacks-queues/index.html
● https://ds1-iiith.vlabs.ac.in/exp/linked-list/basics/overview.html
● https://ds1-iiith.vlabs.ac.in/List%20of%20experiments.html
● https://ds1-iiith.vlabs.ac.in/exp/tree-traversal/index.html
● https://ds1-iiith.vlabs.ac.in/exp/tree-traversal/depth-first-traversal/dft-practice.html
● https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_013501595428077568125 59/overview
Conduct of Practical Examination:

 Experiment distribution
Students are allowed to pick one experiment from the lot 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
Index
Sl Program List CO PO RBT Page
No No
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 CO1 PO3 L3 14
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.
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
CO1 PO3 L3 18
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.
3 Design, Develop and Implement 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
CO2 PO3 L3 21
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
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 CO2 PO3 L3 26
operators: +, -, *, /, % (Remainder), ^ (Power) and
alphanumeric operands
5 Design, Develop and Implement a Program in C for the
following Stack Applications
a. Evaluation of Suffix expression with single digit
operands and operators: +, -, *, /, %, ^ CO2 PO3 L3 29
b. Solving Tower of Hanoi problem with n disks

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) CO3 PO3 L3 35
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
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, Ph No
a. Create a SLL of N Students Data by using front
insertion.
b. Display the status of SLL and count the number of CO3 PO3 L3 39
nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL
(Demonstration of stack)
e. Exit
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 CO3 PO3 L3 43
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
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) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5 z-2xyz 3
b. Find the sum of two polynomials POLY1(x, y, z)
and POLY2(x, y, z) and store the result in CO4 PO3 L3 47
POLYSUM(x,y,z)
Support the program with appropriate functions for each of
the above operations
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
CO4 PO3 L3 54
c. Search the BST for a given element (KEY) and report
the appropriate message
d. Exit

Design, Develop and implement a program in C for the


following operations on Graph (G) of cities
11 a. Create a Graph of N cities using Adjacency Matrix
b. Print all the nodes reachable from a given starting node
in a diagraph using DFS/BFS Method CO5 PO3 L3 60
12. Design and develop a program in C that uses Hash Function H:
K->L as H(K)=K mod m(reminder method) and implement
hashing technique to map a given key K to the address space L.
Resolve the collision (if any) using linear probing. CO5 PO3 L3 67

Course Articulation Matrix


COs POs PSOs
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 3 3 3
CO2 3 3 3 1 3
CO3 3 3 3 1 3
CO4 3 3 3 1 3
CO5 3 3 3 1 3

3 - High Correlation 2 - Medium Correlation 1 – Low Correlation


Data Structures Laboratory – BCSL305 III Semester / B.E.

INTRODUCTION TO DATA STRUCTURES

Data Structure is defined as the way in which data is organized in the memory

location. There are 2 types of data structures:

Linear Data Structure:


In linear data structure all the data are stored linearly or contiguously in the memory. All the data are saved in
continuously memory locations and hence all data elements are saved in one boundary. A linear data structure
isone in which we can reach directly only one element from another while travelling sequentially. The main
advantage, we find the first element, and then it’s easy to find the next data elements. The disadvantage, the
sizeof the array must be known before allocating the memory.

The different types of linear data structures are:


 Array
 Stack
 Queue
 Linked List

Non-Linear Data Structure:


Every data item is attached to several other data items in a way that is specific for reflecting relationships.
Thedata items are not arranged in a sequential structure.

The various types of non linear data structures are:


 Trees
 Graphs

14
Data Structures Laboratory – BCSL305 III Semester / B.E.

EXPERIMENT - 01
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.

ABOUT THE EXPERIMENT:


An Array is a collection of similar / same elements. In this experiment the array can be represented as one / single
dimensional elements.
Menu driven program in c - language to perform various array operations are implemented with the help of user defined
functions as followings;
a. create()
b. display()
c. exit()

ALGORITHM:
Step 1: Create a structure to represent day.
Step 2: Read data for the calendar.
Step 3: Display the weekly activity report
Step 4: Stop.

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Structure to represent a day in the calendar


struct Day
{
char *name;
int date;
char *activity;
};

// Function to create a day in the calendar


struct Day create()
{
struct Day day;
day.name = (char *)malloc(20 * sizeof(char)); // Allocating memory for the name
day.activity = (char *)malloc(100 * sizeof(char)); // Allocating memory for the activity
printf("Enter the day name: ");
scanf("%s", day.name);
printf("Enter the date: ");
scanf("%d", &day.date);
printf("Enter the activity for the day: ");
scanf(" %[^\n]", day.activity);
return day;
}

15
Data Structures Laboratory – BCSL305 III Semester / B.E.

// Function to read data for the calendar


void read(struct Day calendar[], int size)
{
for (int i = 0; i < size; i++)
{
calendar[i] = create();
}
}

// Function to display the weekly activity details report


void display(struct Day calendar[], int size)
{
printf("\nWeekly Activity Details:\n");
for (int i = 0; i < size; i++)
{
printf("Day %d: %s\n", i + 1, calendar[i].name);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n", calendar[i].activity);
printf("\n");
}
}

int main()
{
int weekSize = 7;
struct Day calendar[weekSize];
// Create the calendar
read(calendar, weekSize);
// Display the weekly activity details
display(calendar, weekSize);
// Free dynamically allocated memory
for (int i = 0; i < weekSize; i++)
{
free(calendar[i].name);
free(calendar[i].activity);
}
return 0;
}
Sample Output
Enter the day name: Monday
Enter the date: 161023
Enter the activity for the day: Reading
Enter the day name: Tuesday
Enter the date: 171023
Enter the activity for the day: Coding
Enter the day name: Wednesday
Enter the date: 181023
Enter the activity for the day: Painting
Enter the day name: Thursday
Enter the date: 191023

16
Data Structures Laboratory – BCSL305 III Semester / B.E.

Enter the activity for the day: playing


Enter the day name: Friday
Enter the date: 201023
Enter the activity for the day: shopping
Enter the day name: Saturday
Enter the date: 211023
Enter the activity for the day: Watching Movie
Enter the day name: Sunday
Enter the date: 221023
Enter the activity for the day: Completing Assignments

Weekly Activity Details:


Day 1: Monday
Date: 161023Activity: Reading

Day 2: Tuesday
Date: 171023
Activity: Coding

Day 3: Wednesday
Date: 181023
Activity: Painting

Day 4: Thursday
Date: 191023
Activity: playing

Day 5: Friday
Date: 201023
Activity: shopping

Day 6: Saturday
Date: 211023
Activity: Watching Movie

Day 7: Sunday
Date: 221023
Activity: Completing Assignments

17
Data Structures Laboratory – BCSL305 III Semester / B.E.

EXPERIMENT - 02

Design, Develop and Implement 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. Repost 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.

ABOUT THE EXPERIMENT:


Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null- terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows:

char greeting[] = "Hello";

C language supports a wide range of built-in functions that manipulate null-terminated strings as
follows:

strcpy(s1, s2); Copies string s2 into string s1.


strcat(s1, s2); Concatenates string s2 onto the end of string
s1.strlen(s1); returns the length of string s1.
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
than 0 if s1>s2. S
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

ALGORITHM:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: Search / find the pattern string PAT in the main string STR.
Step 4: if PAT is found then replace all occurrences of PAT in main string STR with REP
string. Step 5: if PAT is not found give a suitable error message.
Step 6: Stop.

PROGRAM CODE:

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

//Declarations
char str[100], pat[50], rep[50],
ans[100];int i, j, c, m, k, flag=0;
void stringmatch()
{
i = m = c = j = 0;
18
Data Structures Laboratory – BCSL305 III Semester / B.E.

while(str[c] ! = '\0')
{
if(str[m] = = pat[i]) // .......matching
{
i++; m++;
if(pat[i] = = '\0') //.... found occurrences.
{
flag = 1;
// .... copy replace string in ans string.
for(k = 0; rep[k] != '\0'; k++, j++)
ans[j] = rep[k];
i = 0;
c = m;
}
} // if ends.
else //... mismatch
{
ans[j] = str[c];
j++; c++;
m = c; i = 0;
}//else ends
} //end of while ans[j] = '\0';
} //end stringmatch()

void main()
{
clrscr();
printf("\nEnter a main string \n"); ]
gets(str);
printf("\nEnter a pattern string \n");
flushall();
gets(pat);
printf("\nEnter a replace string \n");
flushall();
gets(rep);
stringmatch();
if(flag = = 1)
printf("\nThe resultant string is\n %s" , ans);
else
printf("\nPattern string NOT found\n");
getch();
} // end of main

SAMPLE OUTPUT:

RUN 1:
Enter a main string
Test
Enter a pattern string
Te
Enter a replace string
Re
19
Data Structures Laboratory – BCSL305 III Semester / B.E.

The resultant string is


Rest

RUN 2:
Enter a main string
This is Data Structure lab
Enter a pattern string
Data Structure
Enter a replace string
Data structure with C

The resultant string is


This is Data structure with C lab

20
Data Structures Laboratory – BCSL305 III Semester / B.E.

EXPERIMENT - 03
Design, Develop and Implement 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.

ABOUT THE EXPERIMENT:


A stack is an abstract data type (ADT), commonly used in most programming languages. It is named
stack as it behaves like a real-world stack, for example − deck of cards or pile of plates etc.

A real-world stack allows operations at one end only. For example, we can place or remove a card or plate
from top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any given time,
we can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is
placed (inserted or added) last is accessed first. In stack terminology, insertion operation is called
PUSH operation and removal operation is called POP operation.

Below given diagram tries to depict a stack and its operations −

A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can either be
a fixed size one or it may have a sense of dynamic resizing. Here, we are going to implement stack using arrays
which makes it a fixed size stack implementation.
Basic Operations:
 push() - pushing (storing) an element on the stack.
 pop() - removing (accessing) an element from the stack.
To use a stack efficiently we need to check status of stack as well. For the same purpose, the following
functionality is added to stacks;
 . isFull() − check if stack is full.
 isEmpty()-check if stack is empty

21
Data Structures Laboratory – BCSL305 III Semester / B.E.

ALGORITHM:
Step 1: Start.
Step 2: Initialize stack size MAX and top of stack -1.
Step 3: Push integer element on to stack and display the contents of the stack. if stack is full give a message as ‘Stack is
Overflow’.
Step 4: Pop element from stack along with display the stack contents. if stack is empty give a message as ‘Stack is
Underflow’.
Step 5: Check whether the stack contents are Palindrome or not.
Step 6: Stop.

PROGRAM CODE

#include<stdio.h>
#include<string.h>
#include<conio.h>
#define max 5
int st[max],top=-1;
void push(),disp(),palin();
int pop();
void main()
{
int ch,k,item; clrscr();
while(1)
{
printf("MAIN MENU\n");
printf(" 1:Push\n 2:Pop\n 3:Display\n 4:Palindrome\n 5:Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter an item to push\n");
scanf("%d",&item);
push(item);
break;
case 2: k=pop();
if(k)
printf("popped element is %d\n",k);
break;
case 3:disp();
break;
case 4:palin();
break;
case 5:exit(0);
}
}
}
void push(int item)
{
if(top==max-1)

{
printf("Stack overflow\n");
return ;
}

22
Data Structures Laboratory – BCSL305 III Semester / B.E.

st[++top]=item;
}
int pop()
{
if(top==-1)
{
printf("Stack underflow\n");return 0;
}
return(st[top--]);
}
void palin()
{
int i;
char p[100];top=-1;
printf("Enter a number to check for palindrome\n");
fflush(stdin);
gets(p);
for(i=0;i<strlen(p);i++)
push(p[i]-'0');
for(i=0;i<strlen(p)/2;i++)
if((p[i]-'0')!=pop())
{
printf("the number is not palindrome\n");
return;
}
printf("the number is palindrome\n");

}
void disp()
{
int i;
if(top==-1)
{
printf("Stack Empty\n");
return;
}
printf(“the stack contents are”);
for(i=top;i>=0;i--)
printf("|%d|\n",st[i]);
}
}
SAMPLE OUTPUT:

----MAIN MENU----
1.PUSH
2 POP
3.DISPLAY
4.PALINDROME
5.EXIT

Enter Your Choice: 1


Enter an element to be pushed: 2
(-------- AFTER THE 4 TIMES PUSH OPERATION )

23
Data Structures Laboratory – BCSL305 III Semester / B.E.

----MAIN MENU----
PUSH
POP
3.DISPLAY
4.EXIT

Enter Your Choice: 1


Enter an element to be pushed: 9
Stack is Overflow

----MAIN MENU----
1. PUSH
2. POP
3.DISPLAY
4. PALINDROME
4. EXIT
Ener Your Choice: 3
Stack contents are
|4|
|3|
|2|
|1|

----MAIN MENU----
1. PUSH
2. POP
3.DISPLAY
4. PALINDROME
4. EXIT
Ener Your Choice: 2
Poped element is: 4

----MAIN MENU----
1. PUSH
2. POP
3.DISPLAY
4. PALINDROME
4. EXIT
Enter Your Choice: 2
Stack is Underflow

----MAIN MENU----
1.PUSH
2.POP
3.DISPLAY
4.PALINDROME
5.EXIT
Enter Your Choice: 4
Enter the number to check for palindrome:121
The number is palindrome

24
Data Structures Laboratory – BCSL305 III Semester / B.E.

---MAIN MENU----

1. PUSH
2. POP
3.DISPLAY
3. PALINDROME
4. EXIT
Enter Your Choice: 4
Enter the number to check for palindrome:123
The number is not palindrome

25
Data Structures Laboratory – BCSL305 III Semester / B.E.

EXPERIMENT - 04
Design, Develop and Implement 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.

ABOUT THE EXPERIMENT:


Infix: Operators are written in-between their operands. Ex: X + Y
Prefix: Operators are written before their operands. Ex: +X Y
postfix: Operators are written after their operands. Ex: XY+
Examples of Infix, Prefix, and Postfix

Infix Expression Prefix Expression Postfix Expression

A+B +AB AB+

A+B *C +A* BC ABC *+

Convert Infix expression to postfix form: (A+B^D)/(E-F)+G

Symbol Scanned STACK Expression P


(
( ((
A (( A
+ ((+ A
B ((+ AB
^ ( ( +^ AB
D ( ( +^ ABD
) ( A B D^ +
/ (/ A B D^ +
( (/( A B D^ +
E (/( A B D^ +E
- (/ (- A B D^ +E
F (/ (- A B D^ +E
) (/ A B D^ +E -
+ (+ A B D^ +E - /
G (+ A B D^ +E - / G
) A B D^ +E - / G +

26

You might also like