dsa llab
dsa llab
C - 22AIL32 - 2024
Submitted By
Programme
Semester
Section
Session/Batch
Submitted To
Faculty Name
1
S.No. Experiment Aim of Experiment Signature/Date Grade
Date
2
New Horizon College of Engineering
Program - 1
Date of performance: 5th Jan 2025
Aim:
Write a C program that uses a stack to evaluate an infix expression and convert it to a postfix expression.
Input Format
• A string representing the infix mathematical expression
Output Format
• The first line of output represents the converted postfix notation of the infix expression.
• The second line of output represents the result of evaluating the postfix expression.
EvaluateConverted.c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
'||symbol=='*'||symbol=='/'||symbol=='%'||symbol=='^')
return 1;
else
return 0;
}
// Function to convert infix expression to postfix notation
void infixToPostfix(char infix[],char postfix[])
{
int i=0,j=0;
char item,temp;
while(infix[i]!='\0'&&infix[i]!='\n')
{
item=infix[i];
if((item>='A'&&item<='Z')||
(item>='a'&&item<='z')||isdigit(item))
{
postfix[j]=item;
j++;
}
else if(item=='(')
{
push(item);
}
else if(item==')')
{
while(top!=-1&&(temp=pop())!='(')
{
postfix[j]=temp;
j++;
}
}
else if(isOperator(item))
{
while(top!=-1&&precedence(stack[top])>=precedence(item))
{
postfix[j]=pop();
j++;
}
push(item);
}
i++;
}
while(top!=-1)
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
// Function to evaluate a postfix expression
int evaluatePostfixExpression(char postfix[]) {
int stack[MAX_SIZE] ,i=0,j,top=-1,operand1,operand2,result;
char item;
while(postfix[i]!='\0')
{
item=postfix[i];
if(isalnum(item))
{
top++;
stack[top]=(item-'0');
}
else if(isOperator(item))
{
operand2=stack[top];
top--;
operand1=stack[top];
top--;
switch(item)
{
case
'+':result=operand1+operand2;
break;
case '-':result=operand1-operand2;
break;
case
'*':result=operand1*operand2;
break;
case
'/':result=operand1/operand2;
break;
case
'%':result=operand1%operand2;
break;
case '^':result=1;
for(j=0;j<=operand2;j++)
result=result*operand1;
break;
}
top++;
stack[top]=result;
}
i++;
}
return stack[top];
int main() {
char infixExpression[MAX_SIZE];
char postfixExpression[MAX_SIZE];
infixToPostfix(infixExpression, postfixExpression);
return 0;
}
Output:
Test case - 1
User Output
Infix expression:
2+3*4
Postfix expression: 234*+
Result: 14
Test case - 2
User Output
Infix expression:
8%3+6*(2-1)
Postfix expression: 83%621-*+
Result: 8
Result:
Thus the above program is executed successfully and the output has been verified
Program - 2
Date of performance: 22nd Oct 2024
Aim:
Write a C program to delete a node from the end in a doubly linked list
Input Format
Menu Options: The user is prompted with a menu of options:
1. Insert at end
2. Delete at end
3. Traverse the list
4. Exit
Element Input: When choosing to insert at the end, the user will provide a value to be inserted into the DLL.
Output Format
5. Insertion: After inserting an element, the menu will be displayed again.
6. Deletion: After deleting an element, the deleted element's value will be displayed in the format "The
deleted element from DLL : <element>", followed by the menu.
7. Traversal: When traversing, the current elements of the DLL will be displayed in a specific format like "The
elements in DLL are : <element1> <--> <element2> <-->.... <elementn>", followed by the menu.
8. Exit: The program will terminate.
DoubleLL6.c
#include <stdio.h>
#include <stdlib.h>
#include "DelAtEndingInDLL.c"
void main() {
NODE first = NULL;
int x, op;
while(1) {
printf("1.Insert At End 2.Delete at End 3.Traverse the
List 4.Exit\n");
printf("Enter your option : ");
scanf("%d", &op);
switch(op) {
case 1: printf("Enter an element : ");
scanf("%d", &x);
first =
insertAtEndInDLL(first, x);
break;
case 2: if (first == NULL) {
printf("Double Linked
List is empty so deletion is not possible\n");
} else {
first =
deleteAtEndInDLL(first);
}
break;
case 3: if (first == NULL) {
printf("Double Linked
List is empty\n");
} else {
printf("The elements
in DLL are : ");
traverseListInDLL(first);
}
break;
case 4: exit(0);
}
}
}
DelAtEndingInDLL.c
struct node {
int data;
struct node *prev;
struct node *next;
};
typedef struct node * NODE;
NODE createNodeInDLL() {
NODE temp;
temp = (NODE)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
return temp;
}
lastNode=lastNode ->next;
}
temp ->next=NULL;
}
printf("The deleted element from DLL : %d\n",lastNode
->data);
}
free(lastNode);
return head;
}
Output:
Test case - 1
User Output
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
2
Double Linked List is empty so deletion is not possible
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
3
Double Linked List is empty
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
1
Enter an element :
22
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
1
Enter an element :
44
Result:
Thus the above program is executed successfully and the output has been verified
Program - 3
Date of performance: 5th Jan 2025
Aim:
Write a program to create a binary search tree of integers and perform the following operations using linked list.
9. Insert a node
10. In-order traversal
11. Pre-order traversal
12. Post-order traversal
BinarySearchTree.c
#include<stdio.h>
#include<stdlib.h>
#include "InsertAndTraversals.c"
void main() {
int x, op;
BSTNODE root = NULL;
while(1) {
printf("1.Insert 2.Inorder Traversal 3.Preorder
Traversal 4.Postorder Traversal 5.Exit\n");
printf("Enter your option : ");
scanf("%d", &op);
switch(op) {
case 1:
printf("Enter an element to be
inserted : ");
scanf("%d", &x);
root = insertNodeInBST(root,x);
break;
case 2:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(in-order traversal): ");
inorderInBST(root);
printf("\n");
}
break;
case 3:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(pre-order traversal): ");
preorderInBST(root);
printf("\n");
}
break;
case 4:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(post-order traversal): ");
postorderInBST(root);
printf("\n");
}
break;
case 5:
exit(0);
}
}
}
InsertAndTraversals.c
struct node {
int data;
struct node *left, *right;
};
return node;
}
preorderInBST(root->left);
preorderInBST(root->right);
}
}
Output:
Test case - 1
User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
54
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
28
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
62
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
2
Elements of the BST (in-order traversal): 28 54 62
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
3
Test case - 2
User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
100
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
20
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
200
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
10
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
30
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Test case - 3
User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
12
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
12
Element already exists in BST.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Result:
Thus the above program is executed successfully and the output has been verified
Program - 4
Date of performance: 5th Jan 2025
Aim:
Develop a C program to create a Max heap using a given set of integers.
Input Format:
• First Line: An integer n indicates the number of elements in the array.
• Second Line: n space-separated integers representing the elements of the array.
Output Format:
• First Line: A print of the original array elements in the order they were entered which are space-separated.
• Second Line: A print of the array elements after converting it into a max heap which are space-separated.
Note: The partial code has been provided to you in the editor, you are required to fill in the missing parts.
maxHeapCreation.c
#include <stdio.h>
// Function to swap two elements
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
// Function to heapify a subtree rooted at index i
void heapify(int a[],int n,int i)
{
int largest=i;
int left=2*i+1;
int right=2*i+2;
if(left<n &&a[left]>a[largest])
largest=left;
if(right<n &&a[right]>a[largest])
largest=right;
if(largest!=i)
{
swap(&a[i],&a[largest]);
heapify(a,n,largest);
}
}
// Function to build a max heap from a given array
void buildMaxHeap(int a[],int n)
{
for(int i=n/2-1;i>=0;i--){
heapify(a,n,i);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
// Take the number of elements in the array from the user
//printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Declare an array of size n
int arr[n];
// Take array elements from the user
//printf("Enter %d elements for the array:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
//printf("Original array:\n");
printArray(arr, n);
// Build max heap
buildMaxHeap(arr, n);
//printf("Max Heap:\n");
printArray(arr, n);
return 0;
}
Output:
Test case - 1
User Output
5
31425
3 1 4 2 5
5 3 4 2 1
Test case - 2
User Output
3
465
4 6 5
6 4 5
Result:
Thus the above program is executed successfully and the output has been verified
Program - 5
Date of performance: 5th Jan 2025
Aim:
Write a C program to implement Greedy algorithm using Activity Selection Problem.
Note:
• The activities are numbered from 0 to n-1, where n is the number of activities.
• Sort the activities according to their finishing time.
• If the activity has start time greater than or equal to the finish time of previously selected activity, then
select it.
ASP.c
#include<stdio.h>
void sortActivities(int n,int start[],int finish[]){
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(finish[i]>finish[j]){
int temp=finish[i];
finish[i]=finish[j];
finish[j]=temp;
temp=start[i];
start[i]=start[j];
start[j]=temp;
}
}
}
}
void activitySelection(int n,int start[],int finish[]){
sortActivities(n,start,finish);
printf("The following activities are selected: \n");
int i=0;
printf("%d %d\n",start[i],finish[i]);
for(int j=1;j<n;j++){
if(start[j]>=finish[i]){
printf("%d %d\n",start[j],finish[j]);
i=j;
}
}
}
int main(){
int n;
printf("Enter the number of activities: ");
scanf("%d",&n);
int start[n],finish[n];
printf("Enter the start and finish times of each activity:
\n");
for(int i=0;i<n;i++){
scanf("%d %d",&start[i],&finish[i]);
}
activitySelection(n,start,finish);
return 0;
}
Output:
Test case - 1
User Output
Enter the number of activities:
4
Enter the start and finish times of each activity:
1 10
96
85
63
The following activities are selected:
6 3
8 5
9 6
Result:
Thus the above program is executed successfully and the output has been verified
Program - 6
Date of performance: 5th Nov 2024
Aim:
Implement a program using a circular queue to manage print job requests in a printer job scheduling system. The
program should be able to add new print jobs to the circular queue, process and print them, and handle the
circular queue's operations efficiently.
Input Format:
Menu Selection:
Users choose an option from the menu. The available options are:
13. Add Print Job
14. Process Print Job
15. Display Print Jobs
16. Exit
Add Print Job (Option 1):
• First Line : Integer value representing the unique identifier for the print job.
• Second Line : A string representing the description of the print job. Input should be a single line of text.
Process Print Job (Option 2):
• No additional input is required.
Display Print Jobs (Option 3):
• No additional input is required.
Output Format:
After Adding a Print Job:
• Confirmation message indicating that the job has been successfully added to the queue in the format:
"Added Job ID [jobID] to the queue"
After Processing a Print Job:
• Information about the job that has been processed (i.e., removed from the queue) and displays message in
format: "Processing Job ID [jobID]: [description]"
Displaying Print Jobs:
• List of all current print jobs in the queue, showing the Job ID and Description for each in the format "
<JobID>, <description>"
Error or Special Cases:
• Queue Full: If the queue is full when attempting to add a new job, display message in format: Queue is
full
• Queue Empty: If the queue is empty when attempting to process a job or display jobs, display message in
format: Queue is empty
• Invalid Choice: If the user inputs an option not present in the menu, display message in format: Invalid
choice
printJobRequests.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE_SIZE 5
} CircularQueue;
}
q->rear=(q->rear+1)%MAX_QUEUE_SIZE;
q->queue[q->rear]=job;
q->size++;
printf("Added Job ID %d to the queue\n",job.jobID);
}
// Function to remove and return a print job from the circular queue
PrintJob dequeue(CircularQueue *q) {
PrintJob job={0,""};
if(isEmpty(q)){
printf("Queue is empty\n");
return job;
}
job=q->queue[q->front];
q->front=(q->front+1)%MAX_QUEUE_SIZE;
q->size--;
return job;
int main() {
CircularQueue queue;
initQueue(&queue);
int choice;
PrintJob job;
while (1) {
printf("Printer Job Scheduling System\n");
printf("1. Add Print Job\n");
printf("2. Process Print Job\n");
printf("3. Display Print Jobs\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // to consume the newline character left by scanf
switch (choice) {
case 1:
if (isFull(&queue)) {
printf("Queue is full\n");
} else {
scanf("%d", &job.jobID);
getchar(); // to consume the newline character
left by scanf
fgets(job.description, 100, stdin);
job.description[strcspn(job.description, "\n")] =
'\0'; // Remove trailing newline
enqueue(&queue, job);
}
break;
case 2:
job = dequeue(&queue);
if (!isEmpty(&queue)) {
printf("Processing Job ID %d: %s\n", job.jobID,
job.description);
}
break;
case 3:
displayQueue(&queue);
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
Test case - 1
User Output
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
1
23
abc
Added Job ID 23 to the queue
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
24
Invalid choice
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
4
Test case - 2
User Output
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
Result:
Thus the above program is executed successfully and the output has been verified
Program - 7
Date of performance: 5th Jan 2025
Aim:
Implement a program that employs a singly linked list to manage music playlists within a music management
system. The program should enable users to insert new songs at specific positions in the playlist, remove songs if
desired, and facilitate navigation through the playlist in the forward direction.
Input Format:
Menu Selection:
Users will be prompted to select an option from the menu with the following choices:
17. Insert New Song
18. Remove Song
19. Display Playlist
20. Exit
Insert New Song (Option 1):
• First Line: String input representing the title of the song.
• Second Line: String input representing the artist of the song.
• Third Line: Integer indicating where the song should be inserted in the playlist (0 for start or a specific
position).
Remove Song (Option 2):
• First Line: String input representing the title of the song to be removed.
Display Playlist (Option 3):
• No additional input required.
Exit (Option 4):
• No additional input required.
Output Format:
After Inserting a New Song:
• Confirmation message indicating that the song has been added to the playlist is displayed in the format:
Inserted song: [title] by [artist] at position [position]
After Removing a Song:
• Confirmation message indicating that the song has been removed from the playlist in the format:
Removed song: [title] or that the song was not found.
Displaying Playlist:
• List of all current songs in the playlist, showing their titles and artists in the format: Title: [title] Artist:
[artist] which are space-separated
Error or Special Cases:
• Position Out of Range: When trying to insert a song at a position beyond the current length of the playlist
it should display message in the format: Position out of range
• Song Not Found: When trying to remove a song that does not exist in the playlistit should display
message in the format: Song not found
• Invalid Choice: When a user enters an option not present in the menuit should display message in the
format: Invalid choice
sllOperations.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
i++;
}
if(i==position){
prev->next=newnode;
newnode->next=temp;
}
else {
printf("Invalid position\n");
free(newnode);
}
}
}
}
while(temp!=NULL){
printf("%s %s\n",temp->title,temp->artist);
temp=temp->next;
}
}
// Main function
int main() {
Song* playlist = NULL;
int choice, position;
char title[100], artist[100];
while (1) {
printf("Music Playlist Management System\n");
printf("1. Insert New Song\n");
printf("2. Remove Song\n");
printf("3. Display Playlist\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline character
switch (choice) {
case 1:
//printf("Enter song title: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = '\0'; // Remove trailing
newline
case 2:
//printf("Enter the title of the song to remove: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = '\0'; // Remove trailing
newline
removeSong(&playlist, title);
break;
case 3:
displayPlaylist(playlist);
break;
case 4:
// Free the entire playlist before exiting
while (playlist != NULL) {
Song* temp = playlist;
playlist = playlist->next;
free(temp);
}
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
Test case - 1
User Output
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
August
Taylor Swift
0
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
3
August Taylor Swift
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
4
Test case - 2
User Output
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
LoveStory
Taylor Swift
0
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
Hello
Adele
1
Music Playlist Management System
1. Insert New Song
2. Remove Song
Result:
Thus the above program is executed successfully and the output has been verified
Program - 8
Date of performance: 5th Jan 2025
Aim:
In a university, students need to plan their course schedules based on prerequisites. Develop a program using
Topological Sort that helps students determine the correct order to take their courses, ensuring all prerequisite
courses are completed before enrolling in advanced ones.
Input Format
• First Line: An integer representing the total number of courses.
• Second Line: An integer representing the number of prerequisite pairs.
• Third Line: Pairs of integers where the first integer is a prerequisite for the second integer. Each line
contains two integers, u and v, separated by a space, where u must be completed before v.
Output Format
• A space-separated list of course numbers representing a valid order of courses where all prerequisites are
completed before advanced courses. If no valid order is possible due to a cycle in the graph, an
appropriate message is displayed in the format "Cycle present so topological sort is not possible".
topologicalSort.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
int adj[MAX][MAX];
bool visited[MAX];
int stack[MAX];
int top=-1;
void addEdge(int u,int v){
adj[u][v]=1;
}
void dfs(int node,int n){
visited[node]=true;
for(int i=0;i<n;i++){
if(adj[node][i]==1&&!visited[i]){
dfs(i,n);
}
}
stack[++top]=node;
}
bool hasCycleUtil(int node,bool* recursionStack,int n){
if(!visited[node]){
visited[node]=true;
recursionStack[node]=true;
for(int i=0;i<n;i++){
if(adj[node][i]==1){
if(!visited[i]&&hasCycleUtil(i,recursionStack,n)){
return true;
}
else if(recursionStack[i]){
return true;
}
}
}
}
recursionStack[node]=false;
return false;
}
bool hasCycle(int n){
bool recursionStack[MAX]={false};
for(int i=0;i<n;i++){
if(hasCycleUtil(i,recursionStack,n)){
return true;
}
}
return false;
}
void topologicalSort(int n){
for(int i=0;i<n;i++){
visited[i]=false;
}
for(int i=0;i<n;i++){
if(!visited[i]){
dfs(i,n);
}
}
while(top!=-1){
printf("%d ",stack[top--]);
}
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
adj[i][j]=0;
}
}
for(int i=0;i<m;i++){
int u,v;
scanf("%d %d",&u,&v);
addEdge(u,v);
}
for(int i=0;i<n;i++){
visited[i]=false;
}
if(hasCycle(n)){
printf("Cycle present so topological sort is not possible\n");
}
else{
printf("");
topologicalSort(n);
printf("\n");
}
return 0;
}
Output:
Test case - 1
User Output
4
3
01
12
23
0 1 2 3
Test case - 2
User Output
3
3
01
12
20
Cycle present so topological sort is not possible
Result:
Thus the above program is executed successfully and the output has been verified
Program - 9
Date of performance: 10th Dec 2024
Aim:
Implement a program using BFS to manage a social network where each user is a node, and friendships between
users are edges. Find the shortest connection path between any two users in the network.
Input Format:
• First Line: The total number of users in the network. This will define the number of nodes in the graph.
• Second Line: The number of undirected friendship connections n between users. Each friendship is
represented by a pair of integers.
• Next n lines: Each line contains two integers representing a friendship between two users. The first integer
is the user ID of one user, and the second integer is the user ID of the friend.
• Next Line: Two space-separated integers representing the start and end user IDs between which you want
to find the shortest path.
Output Format:
• First Line: The length of the shortest path between the start and end user.
• Second Line: The sequence of user IDs that constitutes the shortest path from the start user to the end
user. Each user ID should be displayed in the order of the path.
shortestDistance.c
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 100
typedef struct{
int adj[MAX][MAX];
int num;
}graph;
void initial(graph *g,int num){
g->num=num;
for(int i=0;i<num;i++){
for(int j=0;j<num;j++){
g->adj[i][j]=0;
}
}
}
void add(graph *g,int u,int v){
g->adj[u][v]=1;
g->adj[v][u]=1;
}
void find(graph *g,int start,int end)
{
int queue[MAX],front=0,rear=0;
bool visited[MAX]={false};
int parent[MAX];
for(int i=0;i<g->num;i++){
parent[i]=-1;
}
queue[rear++]=start;
visited[start]=true;
while(front<rear){
int current= queue[front++];
if(current==end)break;
for(int i=0;i<g->num;i++){
if(g->adj[current][i]&&!visited[i]){
queue[rear++]=i;
visited[i]=true;
parent[i]=current;
}
}
}
if(!visited[end]){
printf("No path found\n");
return;
}
int path[MAX],pathLength=0;
for(int at=end;at!=-1;at=parent[at]){
path[pathLength++]=at;
}
printf("%d\n",pathLength-1);
for(int i=pathLength-1;i>=0;i--){
printf("%d ",path[i]);
}
printf("\n");
}
int main()
{
int num,numf;
scanf("%d",&num);
scanf("%d",&numf);
graph g;
initial(&g,num);
for(int i=0;i<numf;i++){
int u,v;
scanf("%d %d",&u,&v);
add(&g,u,v);
}
int s,e;
scanf("%d %d",&s,&e);
find(&g,s,e);
return 0;
}
Output:
Test case - 1
User Output
4
3
01
12
23
03
3
Test case - 2
User Output
6
6
01
02
13
14
24
35
05
3
0 1 3 5
Result:
Thus the above program is executed successfully and the output has been verified
Program - 10
Date of performance: 5th Jan 2025
Aim:
Develop a program for a city's public transportation system that helps commuters find the shortest travel time
from a single bus stop to all other bus stops using Bellman-Ford.
Input Format:
• First Line: Number of bus stops, n.
• Second Line: Number of edges, m.
• Next m lines: Each edge with its source, destination, and weight (travel time) which are space-separated.
• Next Line: The source bus stop.
Output Format:
• Shortest travel times from the source bus stop to all other bus stops.
• If there is a negative-weight cycle, it will indicate that the graph contains a negative weight cycle.
shortestTravelTime.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
#define INF INT_MAX
typedef struct Edge{
int src,dest,weight;
}Edge;
Edge edges[MAX];
int dist[MAX];
void bellmanFord(int n,int m,int source){
for(int i=0;i<n;i++)
dist[i]=INF;
dist[source]=0;
for(int i=1;i<=n-1;i++)
{
for(int j=0;j<m;j++)
{
int u=edges[j].src;
int v=edges[j].dest;
int weight=edges[j].weight;
if(dist[u]!=INF&&dist[u]+weight<dist[v])
dist[v]=dist[u]+weight;
}
}
for(int j=0;j<m;j++){
int u=edges[j].src;
int v=edges[j].dest;
int weight=edges[j].weight;
if(dist[u]!=INF&&dist[u]+weight<dist[v]){
printf("Graph contains negative weight cycle\n");
return;
}
}
//printf("%d:\n",source);
for(int i=0;i<n;i++){
if(dist[i]==INF){
printf("%d:INF\n",i);
}
else
printf("%d: %d\n",i,dist[i]);
}
}
int main(){
int n,m,source;
//printf("Enter the number of bus stops and edges: ");
scanf("%d %d",&n,&m);
//printf("Enter the edges (source destination weight):\n");
for(int i=0;i<m;i++)
scanf("%d %d %d",&edges[i].src,&edges[i].dest,&edges[i].weight);
//printf("Enter the source bus stop: ");
scanf("%d",&source);
bellmanFord(n,m,source);
return 0;
}
Output:
Test case - 1
User Output
4
5
011
024
122
135
231
0
0: 0
1: 1
2: 3
3: 4
Test case - 2
User Output
3
3
0 1 -1
1 2 -1
2 0 -1
0
Graph contains negative weight cycle
Result:
Thus the above program is executed successfully and the output has been verified
Program - 11
Date of performance: 5th Jan 2025
Aim:
Write a C program to implement unique identifier generation using hashing. Your task is to complete the hash
function to generate a hash value for the provided string.
Input Format:
The input reads the string value.
Output Format:
The output is the final hash value provided by the hash () function, which is an unsigned integer.
uidgenerator.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Identifier {
char input[100];
unsigned int unique_id;
};
int main() {
struct Identifier id;
printf("String: ");
scanf("%99[^\n]", id.input);
id.unique_id = generate_unique_id(id.input);
printf("Unique Identifier for \"%s\": %u\n", id.input,
id.unique_id);
return 0;
}
Output:
Test case - 1
User Output
String:
Hello World
Unique Identifier for "Hello World": 3432422020
Test case - 2
User Output
String:
CodeTantra
Unique Identifier for "CodeTantra": 1083269839
Test case - 3
User Output
String:
coding
Unique Identifier for "coding": 2939880298
Result:
Thus the above program is executed successfully and the output has been verified
Program - 12
Date of performance: 5th Jan 2025
Aim:
Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i]
frequency. Your task is to build the Huffman tree and print all the Huffman codes in the preorder traversal of the
tree.
Note: While merging if two nodes have the same value, then the node that occurs at first will be taken on the left
of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the
subtree and other one to the right.
Example 1:
S = "abcdef"
f[] = {5, 9, 12, 13, 16, 45}
Output:
0 100 101 1100 1101 111
CTC36679.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct MinHeapNode{
char data;
unsigned freq;
struct MinHeapNode*left,*right;
};
struct MinHeap{
unsigned size;
unsigned capacity;
struct MinHeapNode**array;
};
struct MinHeapNode*newNode(char data,unsigned freq){
struct MinHeapNode*temp = (struct
MinHeapNode*)malloc(sizeof(struct MinHeapNode));
temp->data = data;
temp->freq = freq;
temp->left = temp->right = NULL;
return temp;
}
struct MinHeap*createMinHeap(unsigned capacity){
struct MinHeap*minHeap = (struct MinHeap*)malloc(
sizeof(struct MinHeap));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array=(struct MinHeapNode**)malloc(minHeap-
>capacity*sizeof(struct MinHeapNode));
return minHeap;
}
void swapMinHeapNode(struct MinHeapNode**a,struct MinHeapNode**b){
struct MinHeapNode*temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(struct MinHeap*minHeap,int idx){
int smallest = idx;
int left = 2*idx + 1;
int right = 2*idx + 2;
if(left < minHeap->size && minHeap->array[left]->freq<minHeap-
>array[smallest]->freq){
smallest = left;
}
}
struct MinHeapNode* buildHuffmanTree(char data[],int freq[],int size){
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap =
createAndBuildMinHeap(data,freq,size);
while(!isSizeOne(minHeap)){
left = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$' ,left->freq+right->freq);
top->left=left;
top->right=right;
insertMinHeap(minHeap,top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode* root,int arr[],int top){
static int isFirst = 1;
if(root->left){
arr[top] = 0;
printCodes(root->left,arr,top+1);
}if(root->right){
arr[top] = 1;
printCodes(root->right,arr,top+1);
}
if(!(root->left) && !(root->right)){
if(!isFirst){
printf(" ");
}
isFirst = 0;
for(int i=0;i<top;i++){
printf("%d",arr[i]);
}
}
}
void HuffmanCodes(char data[],int freq[],int size){
struct MinHeapNode* root = buildHuffmanTree(data,freq,size);
int arr[100],top=0;
printCodes(root,arr,top);
}
int main(){
char arr[50];
int freq[50];
scanf(" %s",arr);
for(int i=0;i<strlen(arr);i++){
scanf(" %d",&freq[i]);
}
HuffmanCodes(arr,freq,strlen(arr));
return 0;
}
Output:
Test case - 1
User Output
abcdef
5 9 12 13 16 45
0 100 101 1100 1101 111
Test case - 2
User Output
hello
32113
00 010 011 10 11
Result:
Thus the above program is executed successfully and the output has been verified