DS Lab File Harish
DS Lab File Harish
ENGINEERING
DATA STRUCTURES
CO 201
LAB FILE
AIM: Write a program to create a Structure student to store student details, create 5 variables
of student structure and display details.
THEORY:
Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collection of data of different data types.
In this program, Student (structure) is created.
This structure has five members:
name (string), age (integer), roll no (integer), attendance (float) and marks (integer).
Then, a structure variable s is created to store information and display it on the screen.
ALGORITHM:
1) Create a variable of structure to access the records. Here, it is
taken as ‘student’.
2) Create the record variables of student and store it in student’s fields with the help of dot (.)
operator.
3) After all the data is stored, print the records of students using the dot (.) operator.
CODE:
OUTPUT:
EXPERIMENT 2
The steps used in the implementation of Linear Search are listed as follows -
o First, we have to traverse the array elements using a for loop.
o In each iteration of for loop, compare the search element with the current array element,
and -
o If the element matches, then return the index of the corresponding array element.
o If the element does not match, then move to the next element.
o If there is no match or the search element is not present in the given array, return -1.
CODE:
OUTPUT:
EXPERIMENT 3
AIM: Write a program to Implement Binary Search in the C programming language. Assume the
list is already sorted.
THEORY:
A binary search is an advanced type of search algorithm that finds and fetches data from a
sorted list of items. Its core working principle involves dividing the data in the list to half until
the required value is located and displayed to the user in the search result. Binary search is
commonly known as a half-interval search or a logarithmic search.
ALGORITHM:
Followings are the steps to apply binary search:
• Begin with the mid element of the whole array as a search key.
• If the value of the search key is equal to the item, then return an index of the
search key.
• Or if the value of the search key is less than the item in the middle of the interval,
narrow the interval to the lower half.
• Otherwise, narrow it to the upper half.
• Repeatedly check from the second point until the value is found or the interval is
empty.
CODE:
OUTPUT:
EXPERIMENT 4
AIM: Write a program to insert an element at the mid-position in the One-dimensional array.
THEORY:
Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache
friendliness.
One Dimensional Array:
• It is a list of the variable of similar data types.
• It allows random access and all the elements can be accessed with the help of their
index.
• The size of the array is fixed.
• For a dynamically sized array, vector can be used in C++.
ALGORITHM:
1.Get the element value which needs to be inserted.
2.find the size of array.
3. If size of array is odd, then position of element to be added is (n/2) + 2.
4. If it is even then position is (n/2) + 1.
5. Shift all the elements from the last index to position index by 1 position to the right.
insert the new element in middle position.
CODE:
OUTPUT:
EXPERIMENT 5
ALGORITHM:
1. First create a 2d array and fill the data in it.
2. Now, get the row which you want to delete from the array.
3. Now, run a loop and exclude the row number which you want to delete.
4. Print the remaining array.
5. Exit from the code.
CODE:
OUTPUT:
EXPERIMENT 6
AIM: Write a C/C++ program to Merge an array of size into another array of size m + n.
THEORY:
To merge two arrays in C++ programming, you have to ask from user to enter the size and
elements for both the array. Then merge these two given arrays into a third array as shown in
the program given below:
Note - At the time of receiving array's elements, we've applied the merge operation. That is,
elements received by user gets initialized to a third array one by one.
ALGORITHM:
1. We traverse both given arrays.
2. One by one put their elements into combined array.
3. After one of the arrays is exhausted, we put remaining elements of the other
array.
4. Print the combined array.
CODE:
OUTPUT:
EXPERIMENT 7
AIM: Write a program to reverse an array or string, with best TC and SC.
THEORY:
In many situations, we may need to reverse a string/array in C++ programming. It may include
just printing a reversed string. Or maybe in some cases need to reverse the string permanently
at its address. Reversing a string refers to the operation on a string, by which the sequence of
characters in it gets reversed.
ALGORITHM:
1. Define a array and another empty array to store the reversed string.
2. Now, iterate the array from last and store a character from back into variable reversed
array.
3. At the end of the loop, reversed array will hold the reverse of the string.
CODE:
OUTPUT:
EXPERIMENT 8
AIM: Write a program to find kth largest element in an array, using best TC.
THEORY:
The given task is to find the Kth largest element in an array. Here we must note that the
question is one level higher compared to finding the largest or the smallest element in an array.
In this task, ‘K’ refers to the cardinality of array values.
ALGORITHM:
First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in order.
4. The above process goes on until the last element.
2. Remaining Iteration
5. The same process goes on for the remaining iterations.
6. After each iteration, the largest element among the unsorted elements is placed
at the end.
• Now array is sorted, insert the k value to get that number.
• Print that number.
• Exit.
CODE:
OUTPUT:
EXPERIMENT 9
ALGORITHM:
• Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
• Declare all the functions used in stack implementation.
• Create a one dimensional array with fixed size (int stack[SIZE])
• Define a integer variable 'top' and initialize with '-1'. (int top = -1)
• In main method, display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.
CODE:
//CODE by HARISH(2K21/CO/176)
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int count = 0;
struct stack {
int items[MAX];
int top;
};
// Add elements
void push(st *s, int newitem) {
if (isfull(s)) {
printf("STACK FULL");
} else {
s->top++;
s->items[s->top] = newitem;
}
count++;
}
// Remove element
void pop(st *s) {
if (isempty(s)) {
printf("\n STACK EMPTY \n");
} else {
printf("popped item = %d", s->items[s->top]);
s->top--;
}
count--;
printf("\n");
}
// Print
void printStack(st *s) {
printf("Stack:\n");
for (int i = 0; i < count; i++) {
printf("element %d : ",i+1);
printf("%d \n", s->items[i]);
}
printf("\n");
}
// main function
int main() {
int ch;
st *s = (st *)malloc(sizeof(st));
createEmptyStack(s);
push(s, 99);
push(s, 21);
push(s, 38);
push(s, 64);
printStack(s);
pop(s);
OUTPUT:
EXPERIMENT 10
The balanced parentheses problem is one of the common programming problems that is also
known as Balanced brackets. This problem is commonly asked by the interviewers where we
have to validate whether the brackets in a given string are balanced on not.
Characters such as "(", ")", "[", "]", "{", and "}" are considered brackets.
ALGORITHM:
• Declare a character stack S.
• Now traverse the expression string exp.
1. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it
to stack.
2. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop
from stack and if the popped character is the matching starting bracket
then fine else brackets are not balanced.
• After complete traversal, if there is some starting bracket left in stack then “not
balanced”
CODE:
//CODE by HARISH(2K21/CO/176)
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct stack {
char stck[MAX];
int top;
}s;
else {
s.top = s.top + 1;
s.stck[s.top] = item;
}
}
void pop() {
if (s.top == -1)
printf("Stack is Empty\n");
else
s.top = s.top - 1;
}
else if(checkPair(s.stck[s.top],expr[i]))
{
pop();
continue;
}
return 0;
}
}
return 1;
}
int main() {
int i = 0;
s.top = -1;
char exp1[MAX]="{{(())}}{}()";
char exp2[MAX]="{{(}{(})";
OUTPUT:
EXPERIMENT 11
ALGORITHM:
Queue operations work as follows:
• two pointers front and rear.
• front track the first element of the queue.
• rear track the last element of the queue.
• initially, set value of front and rear to -1.
Enqueue Operation
• check if the queue is full.
• for the first element, set the value of front to 0.
• increase the rear index by 1.
• add the new element in the position pointed to by rear.
Dequeue Operation
• check if the queue is empty.
• return the value pointed by front.
• increase the front index by 1.
• for the last element, reset the values of front and rear to -1.
CODE:
//CODE by HARISH(2K21/CO/176)
#include <stdio.h>
#define SIZE 5
// insertion
void enQueue(int value) {
if (rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted : %d", value);
}
}
// deletion
void deQueue() {
if (front == -1)
printf("\nQueue is Empty!!");
else {
printf("\nDeleted : %d", items[front]);
front++;
if (front > rear)
front = rear = -1;
}
}
// display
void display() {
if (rear == -1)
printf("\nQueue is Empty!!!");
else {
int i;
printf("\nQueue elements are:\n");
for (i = front; i <= rear; i++)
printf("%d ", items[i]);
}
printf("\n");
}
int main() {
deQueue();
enQueue(6);
enQueue(2);
enQueue(63);
enQueue(94);
enQueue(85);
enQueue(86);
display();
deQueue();
display();
return 0;
}
OUTPUT:
EXPERIMENT 12
1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
3 - Create a one dimensional array with above defined SIZE (int cQueue[SIZE])
4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -
1, rear = -1)
5 - Implement main method by displaying menu of operations list and make suitable
function calls to perform operation selected by the user on circular queue.
1- Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front == rear+1))
2 - If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate
the function.
3 - If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then set rear =
-1.
4 - Increment rear value by one (rear++), set queue[rear] = value and check 'front == -1'
if it is TRUE, then set front = 0.
3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
4 - Check whether 'front <= rear', if it is TRUE, then display 'queue[i]' value and increment
'i' value by one (i++). Repeat the same until 'i <= rear' becomes FALSE.
5 - If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i' value by one
(i++). Repeat the same until'i <= SIZE - 1' becomes FALSE.
6 - Set i to 0.
7 - Again display 'cQueue[i]' value and increment i value by one (i++). Repeat the same
until 'i <= rear' becomes FALSE.
CODE:
//CODE by HARISH(2K21/CO/176)
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
// insertion
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted : %d", element);
}
}
// Removal
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
}
else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element : %d \n", element);
return (element);
}
}
// Display
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front index : %d ", front);
printf("\n Items : ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear index : %d \n", rear);
}
}
int main() {
deQueue();
enQueue(15);
enQueue(20);
enQueue(3);
enQueue(54);
enQueue(65);
// Fails to enqueue because front == 0 && rear == SIZE - 1
enQueue(40);
display();
deQueue();
display();
enQueue(50);
display();
// Fails to enqueue because front == rear + 1
enQueue(60);
return 0;
}
OUTPUT: