0% found this document useful (0 votes)
21 views

23UDSSBP301 DS_Lab

Jahhejehheidjjjjjjjjsjj

Uploaded by

varnikhasree057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

23UDSSBP301 DS_Lab

Jahhejehheidjjjjjjjjsjj

Uploaded by

varnikhasree057
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

K.S.

RANGASAMY COLLEGE OF ARTS AND SCIENCE (AUTONOMOUS)

TIRUCHENGODE – 637 215

DEPARTMENT OF CS – DATA SCIENCE

III SEMESTER (2023 ONWARDS)

SEC- II: DATA STRUCTURE USING C LAB

SUBJECT CODE: 23UDSSBP301

LAB MANUAL

Prepared by Approved by Issued by


HOD PRINCIPAL
S.No PROGRAMS Hrs

1. Program to implement various operators. 3

2. Program to perform Singly Linked Lists Operations. 3

3. Program to implement stack (its operations) using Arrays. 3

4. Program to implement Queues (its operations) using Linked Lists. 3

5. Program to implement the Tree Traversal method. 3

6. Program to implement Depth First Search (DFS) Graphs Traversal methods. 3

Program to perform Binary Search operations for a key value in a given list of
7. 3
integers.

Program to implement Bubble sort and selection sort given list of integers in
8. 3
ascending order.

9. Program to implement Heap sort 3

10. Program to implement Quick sort 3


1. Program to implement various operators.
Aim: To write to various operators.
Working of arithmetic operators:
#include <stdio.h>
int main()
{
int a = 25, b = 5;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);
return 0;
}
Output:
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26
C program to illustrate the relational operators

#include <stdio.h>
int main()
{
int a = 25, b = 5;
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);

return 0;
}

Output:
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
C program to illustrate the logical operators

#include <stdio.h>
int main()
{
int a = 25, b = 5;
printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);

return 0;
}
Output:
a && b : 1
a || b : 1
!a: 0
Working of increment and decrement operators

#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output:
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Result:
Those the above operators are executed successfully.
2. Program to perform Singly Linked Lists Operations.
Aim: The aim is to implement basic operations on a singly linked list using data structures in C

Procedure:
Step 1: Define the Node Structure:
 Create a structure to represent a node in the linked list, which includes a data field and a
pointer to the next node.
Step 2: Insertion Operations:
 At the Beginning: Create a new node, set its next to the current head, and update the
head to the new node.
 At the End: Traverse the list to find the last node and append the new node.
 At a Specific Position: Traverse to the node before the desired position, then insert the
new node.
Step 3: Deletion Operations:
 At the Beginning: Update the head to the next node and free the old head node.
 At the End: Traverse to the second-to-last node, update its next to NULL, and free the
last node.
 At a Specific Position: Traverse to the node before the desired position, update its next to
skip the node to be deleted, and free the node.
Step 4: Display the List: Traverse through the list and print the data of each node.
Step 5: Search for a Value: Traverse the list to find a node with the specified value.

#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void deleteStart (struct Node **head)
{
struct Node *temp = *head;
if (*head == NULL)
{
printf ("Linked List Empty, nothing to delete");
return;
}
*head = (*head)->next;
printf ("\n%d deleted\n", temp->data);
free (temp);
}
void insertStart (struct Node **head, int data)
{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));

newNode->data = data;
newNode->next = *head;
*head = newNode;
printf ("\n%d Inserted\n", newNode->data);
}
void display (struct Node *node)
{
printf ("\nLinked List: ");
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
printf ("\n");
}
int main ()
{
struct Node *head = NULL;
insertStart (&head, 100);
insertStart (&head, 60);
insertStart (&head, 40);
insertStart (&head, 20);

display (head);

deleteStart (&head);
deleteStart (&head);
display (head);

return 0;
}

OUTPUT

100 Inserted
80 Inserted
60 Inserted
40 Inserted
20 Inserted
Linked List: 20 40 60 80 100
20 deleted
40 deleted
Linked List: 60 80 100

Result:
Those the above Singly Linked Lists Operations are executed successfully
3. Program to implement stack (its operations) using Arrays.

Aim: To write a stack operation using arrays.


Procedure:
Step 1: Start the Program
Step 2: Initialize an array to represent the stack.
Step 3: Use the end of the array to represent the top of the stack.
Step 4: Implement push (add to end), pop (remove from the end), and peek (check end)
operations, ensuring to handle empty and full stack conditions
Step 5: Stop the Program

Coding:
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}
OUTPUT:
Enter the size of STACK [MAX=100]:10

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

24
12
Press Next Choice
Enter the Choice:4

EXIT POINT

Result:
This program successfully implements a stack using an array and performs push, pop, and
display operations, demonstrating basic stack functionality.
4. Program to implement Queues (its operations) using Linked Lists.
Aim:
To implement a queue using arrays and perform basic queue operations (enqueue,
dequeue, display).

Algorithm:

1. Initialize the Queue:


o Set the front and rear pointers to -1.

o Define the maximum size of the queue.


2. Enqueue Operation:
o Check if the queue is full.
o If not, increment the rear pointer and add the new element.
3. Dequeue Operation:
o Check if the queue is empty.
o If not, retrieve the front element and increment the front pointer.
o If the queue becomes empty after dequeue, reset pointers.
4. Display Operation:
o Traverse from the front to the rear pointer to print the elements.

Program:

#include <stdio.h>
#define MAX 100
// Queue structure
typedef struct
{
int arr[MAX];
int front, rear;
} Queue;

// Initialize queue
void init(Queue *q)
{
q->front = q->rear = -1;
}

// Check if the queue is empty


int isEmpty(Queue *q)
{
return q->front == -1;
}
// Check if the queue is full
int isFull(Queue *q)
{
return q->rear == MAX - 1;
}

// Enqueue operation
void enqueue(Queue *q, int value)
{
if (isFull(q))
{
printf("Queue Overflow\n");
return;
}
if (isEmpty(q))
{
q->front = 0;
}
q->arr[++q->rear] = value;
printf("%d enqueued to queue\n", value);
}
// Dequeue operation
int dequeue(Queue *q)
{
if (isEmpty(q))
{
printf("Queue Underflow\n");
return -1;
}
int value = q->arr[q->front];
if (q->front == q->rear)
{
q->front = q->rear = -1; // Queue becomes empty
} else
{
q->front++;
}
return value;
}
// Display queue
void display(Queue *q)
{
if (isEmpty(q))
{
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (int i = q->front; i <= q->rear; i++)
{
printf("%d ", q->arr[i]);
}
printf("\n");
}

int main()
{
Queue q;
init(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
display(&q);
printf("%d dequeued from queue\n", dequeue(&q));
display(&q);
return 0;
}

Output:

10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
Queue elements: 10 20 30
10 dequeued from queue
Queue elements: 20 30

Result: The program successfully implements a queue using an array and performs enqueue,
dequeue, and display operations.
5. Program to implement the Tree Traversal method.

Aim:
To implement tree traversal methods (inorder, preorder, and postorder) for binary trees in
C.

Algorithm:

1. Define the Tree Structure:


o Create a node structure with data, left, and right pointers.

2. Implement Traversal Methods:


o Inorder Traversal: Traverse left subtree, visit node, traverse right subtree.
o Preorder Traversal: Visit node, traverse left subtree, traverse right subtree.
o Postorder Traversal: Traverse left subtree, traverse right subtree, visit node.
3. Create a Sample Tree and Call Traversal Functions:
o Build a sample binary tree.
o Call traversal functions and display results.

Program:

#include <stdio.h>
#include <stdlib.h>
// Tree Node structure
typedef struct Node
{
int data;
struct Node* left;
struct Node* right;
} Node;

// Create a new tree node


Node* createNode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Inorder Traversal
void inorder(Node* root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

// Preorder Traversal
void preorder(Node* root) {
if (root != NULL)
{
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}

// Postorder Traversal
void postorder(Node* root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}

int main()
{
// Create sample tree
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

// Traverse and print


printf("Inorder Traversal: ");
inorder(root);
printf("\nPreorder Traversal: ");
preorder(root);
printf("\nPostorder Traversal: ");
postorder(root);
printf("\n");

return 0;
}

Output:

Inorder Traversal: 4 2 5 1 3
Preorder Traversal: 1 2 4 5 3
Postorder Traversal: 4 5 2 3 1

Result:

The program correctly implements and demonstrates the three primary tree traversal
methods for binary trees, showcasing their respective output sequences.

6. Program to implement Depth First Search (DFS) Graphs Traversal methods.

Aim: To implement Depth First Search (DFS) for graph traversal in C.

Algorithm:

Step 1: Graph Representation:

 Use an adjacency matrix or adjacency list to represent the graph.

Step 2: DFS Implementation:


 Recursive Approach:
 Start from a source vertex.
 Mark the vertex as visited.
 Recursively visit all adjacent unvisited vertices.

Step 3: Create a Sample Graph and Perform DFS:


 Build a sample graph.
 Call the DFS function from a starting vertex.
Program:
#include <stdio.h>
#include <stdbool.h>

#define MAX_VERTICES 100


// Graph structure
typedef struct
{

int adjMatrix[MAX_VERTICES][MAX_VERTICES];

int numVertices;

} Graph;
// Initialize the graph
void initGraph(Graph *g, int numVertices)
{
g->numVertices = numVertices;
for (int i = 0; i < numVertices; i++)
{
for (int j = 0; j < numVertices; j++)
{
g->adjMatrix[i][j] = 0;
}

// Add an edge
void addEdge(Graph *g, int start, int end)
{
g->adjMatrix[start][end] = 1;
g->adjMatrix[end][start] = 1; // For undirected graph
}
// DFS function
void dfs(Graph *g, int vertex, bool visited[])
{
visited[vertex] = true;
printf("%d ", vertex);
for (int i = 0; i < g->numVertices; i++)

if (g->adjMatrix[vertex][i] == 1 && !visited[i])

dfs(g, i, visited);

int main()

{
Graph g;
initGraph(&g, 5); // Create a graph with 5 vertice
addEdge(&g, 0, 1);
addEdge(&g, 0, 4);
addEdge(&g, 1, 2);
addEdge(&g, 1, 3);
addEdge(&g, 2, 4);
addEdge(&g, 3, 4);
bool visited[MAX_VERTICES] = {false};
printf("Depth First Search starting from vertex 0:\n");
dfs(&g, 0, visited);

return 0;
}

Output:

Depth First Search starting from vertex 0:

01243

Result:

The program successfully implements Depth First Search (DFS) using an adjacency matrix
representation of the graph.
.
7. Program to perform Binary Search operations for a key value in a given list of integers.

Aim:
To implement binary search operations for finding a key value in a sorted list of integers.

Algorithm:
Step1: Initialize the list and the key value.
Step2: Set low, high, and middle indices.
Step3: While low ≤ high:
Step4: Compute the middle index.
Step5: If the key is at the middle index, return the index.
Step6: Else If the key is less than the value at the middle index, update the high index.
Step7: Else update the low index.
Step: Return -1 if the key is not found.

Program:

#include <stdio.h>
int binarySearch(int arr[], int size, int key)
{
int low = 0;
int high = size - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (arr[mid] == key)
{
return mid; // Key found
}
else if (arr[mid] < key)
{
low = mid + 1; // Search in the right half
}
else
{
high = mid - 1; // Search in the left half
}
}
return -1; // Key not found
}
int main()
{
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int size = sizeof(arr) / sizeof(arr[0]);
int key = 14;
int result = binarySearch(arr, size, key);
if (result != -1)
{
printf("Key %d found at index %d\n", key, result);
}
else
{
printf("Key %d not found in the array\n", key);
}
return 0;
}

Output:

Key 14 found at index 6

Result:

The binary search algorithm efficiently finds the key value in the sorted list, providing the
index of the key if it is present or indicating if it is not found
8. Program to implement Bubble sort and selection sort given list of integers in ascending
order.

Aim: To implement Bubble Sort and Selection Sort algorithms for sorting a list of integers in
ascending order in C.

Algorithm:

Bubble Sort:
1. Compare adjacent elements and swap them if they are in the wrong order.
2. Repeat the process for all elements, reducing the comparison range each time.
3. Continue until no swaps are needed.

Selection Sort:
1. Find the minimum element in the unsorted portion of the list.
2. Swap it with the first unsorted element.
3. Move the boundary of the sorted portion one element to the right.
4. Repeat until the entire list is sorted.

Program:

#include <stdio.h>
#define SIZE 5
// Function to perform Bubble Sort

void bubbleSort(int arr[], int n)


{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to perform Selection Sort


void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
// Swap
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Function to print an array
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

int main()
{
int arr1[SIZE] = {64, 25, 12, 22, 11};
int arr2[SIZE] = {64, 25, 12, 22, 11};

printf("Original array:\n");
printArray(arr1, SIZE);

// Bubble Sort
bubbleSort(arr1, SIZE);
printf("Array sorted with Bubble Sort:\n");
printArray(arr1, SIZE);

// Selection Sort
selectionSort(arr2, SIZE);
printf("Array sorted with Selection Sort:\n");
printArray(arr2, SIZE);

return 0;
}

Output:

Original array:
64 25 12 22 11
Array sorted with Bubble Sort:
11 12 22 25 64
Array sorted with Selection Sort:
11 12 22 25 64

Result:

The program implements both Bubble Sort and Selection Sort algorithms, sorting a list of
integers in ascending order.

9. Program to implement Heap sort

Aim: To implement Heap Sort, a comparison-based sorting algorithm, to sort an array of integers
in ascending order in C.

Algorithm:
Step 1: Heapify:
 Convert the array into a max-heap. A max-heap is a binary tree where the parent node is
greater than or equal to its children.
 For each node, ensure it satisfies the heap property by adjusting the subtree rooted at that
node.
Step 2: Heap Sort:
 Extract the maximum element (root of the heap) and place it at the end of the array.
 Reduce the heap size by one and heapify the root to maintain the heap property.
 Repeat the process until the heap is empty.

Program:

#include <stdio.h>
#define SIZE 10
// Function to heapify a subtree rooted at index i
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child

// If left child is larger than root


if (left < n && arr[left] > arr[largest])
{
largest = left;
}

// If right child is larger than largest so far


if (right < n && arr[right] > arr[largest])
{

largest = right;
}
// If largest is not root
if (largest != i)
{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}

// Function to perform heap sort


void heapSort(int arr[], int n)
{
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--)
{
heapify(arr, n, i);
}

// Extract elements from the heap one by one


for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

// Call heapify on the reduced heap


heapify(arr, i, 0);
}
}

// Function to print an array


void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[SIZE] = {12, 11, 13, 5, 6, 7, 8, 9, 10, 1};

printf("Original array:\n");
printArray(arr, SIZE);

heapSort(arr, SIZE);

printf("Sorted array:\n");
printArray(arr, SIZE);

return 0;
}

Output:
Original array:
12 11 13 5 6 7 8 9 10 1
Sorted array:
1 5 6 7 8 9 10 11 12 13

Result: The program successfully implements Heap Sort.

10. Program to implement Quick sort

Aim: To implement Quick Sort, a comparison-based sorting algorithm, to sort an array of integers
in ascending order in C.

Algorithm:

1. Partitioning:
o Choose a pivot element from the array.

o Rearrange the array such that all elements less than the pivot come before it and all
elements greater come after it.
o Place the pivot in its correct position in the sorted array.
2. Recursion:
o Recursively apply the above steps to the sub-arrays of elements less than and
greater than the pivot.

Program:

#include <stdio.h>
#define SIZE 10

// Function to swap two elements


void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

// Function to partition the array


int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // Choose the rightmost element as pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j < high; j++)


{
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Function to perform Quick Sort


void quickSort(int arr[], int low, int high)
{
if (low < high)
{
// Partition the array
int pi = partition(arr, low, high);

// Recursively sort the sub-arrays


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print an array


void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

int main()
{
int arr[SIZE] = {34, 7, 23, 32, 5, 62, 32, 67, 4, 18};

printf("Original array:\n");
printArray(arr, SIZE);

quickSort(arr, 0, SIZE - 1);

printf("Sorted array:\n");
printArray(arr, SIZE);

return 0;
}

Output:

Original array:
34 7 23 32 5 62 32 67 4 18
Sorted array:
4 5 7 18 23 32 32 34 62 67

Result: The program implements Quick Sort effectively, demonstrating sorting of an integer
array in ascending order.

You might also like