0% found this document useful (0 votes)
19 views31 pages

DS Lab File Harish

lab file of data structure of dtu

Uploaded by

dtuharshkr
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)
19 views31 pages

DS Lab File Harish

lab file of data structure of dtu

Uploaded by

dtuharshkr
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/ 31

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

DATA STRUCTURES

CO 201

LAB FILE

SUBMITTED TO: SUBMITTED BY:


PROF. ANUKRITI KAUSHAL HARISH (2K21/CO/176)
EXPERIMENT 1

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

AIM: Write a program to Implement Linear Search in the C programming language.


THEORY:
A linear search, also known as a sequential search, is a method of finding an element within a
list. It checks each element of the list sequentially until a match is found or the whole list has
been searched.
ALGORITHM:

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

AIM: Write a program to delete a given row in the two-dimensional array.


THEORY:
2-Dimensional Array:
• It is a list of lists of the variable of the same data type.
• It also allows random access and all the elements can be accessed with the help of
their index.
• It can also be seen as a collection of 1D arrays. It is also known as the Matrix.
• Its dimension can be increased from 2 to 3 and 4 so on.
• They all are referred to as a multi-dimension array.
• The most common multidimensional array is a 2D array.

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

AIM: Write a program to implement a stack using Array in C.


THEORY:
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means
the last element inserted inside the stack is removed first.
There are some basic operations that allow us to perform different actions on a stack.
• Push: Add an element to the top of a stack
• Pop: Remove an element from the top of a stack
• IsEmpty: Check if the stack is empty
• IsFull: Check if the stack is full
• Peek: Get the value of the top element without removing it

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.

Push(value) - Inserting value into the stack

• Check whether stack is FULL. (top == SIZE-1)


• If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the
function.
• If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

Pop() - Delete a value from the Stack

• Check whether stack is EMPTY. (top == -1)


• If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
• If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
Display() - Displays the elements of a Stack
We can use the following steps to display the elements of a stack...
• Check whether stack is EMPTY. (top == -1)
• If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
• If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value
and decrement i value by one (i--).
• Repeat above step until i value becomes '0'.

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

typedef struct stack st;

void createEmptyStack(st *s) {


s->top = -1;
}

// Check if the stack is full


int isfull(st *s) {
if (s->top == MAX - 1)
return 1;
else
return 0;
}

// Check if the stack is empty


int isempty(st *s) {
if (s->top == -1)
return 1;
else
return 0;
}

// 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);

printf("\nAfter popping out\n");


printStack(s);
}

OUTPUT:
EXPERIMENT 10

AIM: C Program To Check For Balanced Brackets In An Expression Using Stack.


THEORY:

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>

#define MAX 100

struct stack {
char stck[MAX];
int top;
}s;

void push(char item) {


if (s.top == (MAX - 1))
printf("Stack is Full\n");

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

int checkPair(char val1,char val2){


return (( val1=='(' && val2==')' )||( val1=='[' && val2==']' )||( val1=='{' && val2=='}' ));
}

int checkBalanced(char expr[], int len){

for (int i = 0; i < len; i++)


{
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{')
{
push(expr[i]);
}
else
{
if (s.top == -1)
return 0;

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]="{{(}{(})";

int len1 = strlen(exp1);


int len2= strlen(exp2);

printf("input string : %s",exp1);


checkBalanced(exp1, len1)?printf("\nstring is Balanced\n"): printf("\nstring is Not
Balanced\n");
printf("input string : %s",exp2);
checkBalanced(exp2, len2)?printf("\nstring is Balanced\n"): printf("\nstring is Not
Balanced\n");
return 0;
}

OUTPUT:
EXPERIMENT 11

AIM: Write a program to implement a queue in C.


THEORY:
A queue is a useful data structure in programming. It is similar to the ticket queue outside a
cinema hall, where the first person entering the queue is the first person who gets the ticket.
Queue follows the First In First Out (FIFO) rule - the item that goes in first is the item that
comes out first.

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

int items[SIZE], front = -1, rear = -1;

// 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

AIM: Write a program to Implement circular queue in C.


THEORY:
A circular queue is the extended version of a regular queue where the last element is connected
to the first element. Thus forming a circle-like structure. The circular queue solves the major
limitation of the normal queue. In a normal queue, after a bit of insertion and deletion, there
will be non-usable empty space.
ALGORITHM:

1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.

2 - Declare all user defined functions used in circular queue implementation.

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.

EnQueue - Inserting value into the 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.

deQueue() - Deleting a value from the Circular Queue

1 - Check whether queue is EMPTY. (front == -1 && rear == -1)


2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and
terminate the function.

3 - If it is NOT EMPTY, then display queue[front] as deleted element and increment


the front value by one (front ++). Then check whether front == SIZE, if it is TRUE, then
set front = 0. Then check whether both front - 1 and rear are equal (front -1 == rear), if
it TRUE, then set both front and rear to '-1' (front = rear = -1).

Display() - Displays the elements of a Circular Queue

1 - Check whether queue is EMPTY. (front == -1)

2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.

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;

// Check if the queue is full


int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}

// Check if the queue is empty


int isEmpty() {
if (front == -1) return 1;
return 0;
}

// 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:

You might also like