0% found this document useful (0 votes)
13 views36 pages

DSA assignment

The document outlines multiple C programming projects, including a Library Management System using linked lists, a Browser History Management system using circular linked lists, Undo-Redo functionality using stacks, a Customer Service Simulation using queues, and a Task Scheduling System using a min-heap. Each project includes specifications for functionality, data structures to be used, and sample code implementations. The document serves as a guide for implementing these systems with terminal input/output interactions.

Uploaded by

saimanjithp
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)
13 views36 pages

DSA assignment

The document outlines multiple C programming projects, including a Library Management System using linked lists, a Browser History Management system using circular linked lists, Undo-Redo functionality using stacks, a Customer Service Simulation using queues, and a Task Scheduling System using a min-heap. Each project includes specifications for functionality, data structures to be used, and sample code implementations. The document serves as a guide for implementing these systems with terminal input/output interactions.

Uploaded by

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

1.

Library Management System using Linked Lists


• Write a C program to create a simple library management system using a doubly
linked list. The program should allow adding, deleting, and searching for books by
title. Each book should have a unique ID, title, and author.
Library Management System using Linked Lists
• Use a doubly linked list to store book details (ID, title, author).
• Implement functions for adding, deleting, and searching books.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Book {
int id;
char title[100];
char author[100];
struct Book* prev;
struct Book* next;
} Book;

Book* head = NULL;

Book* createBook(int id, char* title, char* author) {


Book* newBook = (Book*)malloc(sizeof(Book));
newBook->id = id;
strcpy(newBook->title, title);
strcpy(newBook->author, author);
newBook->prev = NULL;
newBook->next = NULL;
return newBook;
}

void addBook(int id, char* title, char* author) {


Book* newBook = createBook(id, title, author);
if (head == NULL) {
head = newBook;
} else {
Book* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newBook;
newBook->prev = temp;
}
printf("Book added successfully!\n");
}

1
void deleteBook(char* title) {
if (head == NULL) {
printf("No books in the library.\n");
return;
}
Book* temp = head;
while (temp != NULL) {
if (strcmp(temp->title, title) == 0) {
if (temp->prev != NULL) {
temp->prev->next = temp->next;
} else {
head = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
printf("Book deleted successfully!\n");
return;
}
temp = temp->next;
}
printf("Book not found.\n");
}

void searchBook(char* title) {


if (head == NULL) {
printf("No books in the library.\n");
return;
}
Book* temp = head;
while (temp != NULL) {
if (strcmp(temp->title, title) == 0) {
printf("Book found!\nID: %d\nTitle: %s\nAuthor: %s\n", temp->id, temp->title,
temp->author);
return;
}
temp = temp->next;
}
printf("Book not found.\n");
}

void displayMenu() {
printf("Library Management System\n");
printf("1. Add Book\n");
printf("2. Delete Book\n");
printf("3. Search Book\n");
printf("4. Exit\n");
printf("Enter your choice: ");
2
}

int main() {
int choice, id;
char title[100], author[100];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter book ID: ");
scanf("%d", &id);
getchar();
printf("Enter book title: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = 0;
printf("Enter book author: ");
fgets(author, 100, stdin);
author[strcspn(author, "\n")] = 0;
addBook(id, title, author);
break;
case 2:
getchar();
printf("Enter book title to delete: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = 0;
deleteBook(title);
break;
case 3:
getchar();
printf("Enter book title to search: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = 0;
searchBook(title);
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

3
OUTPUT :

2. Browser History Management using Circular Linked List


• Implement a C program that simulates a browser history management system
using a circular linked list. The program should allow users to visit new URLs, go
back to the previous URL, and display the current URL.
Browser History Management using Circular Linked List :
• Use a circular linked list to store URLs.
• Implement functions to visit a new URL, go back to the previous URL, and
display the current URL.
• Use terminal input and output to interact with the user
A)
4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct URLNode {


char url[100];
struct URLNode* next;
struct URLNode* prev;
} URLNode;

URLNode* current = NULL;

URLNode* createURLNode(char* url) {


URLNode* newNode = (URLNode*)malloc(sizeof(URLNode));
strcpy(newNode->url, url);
newNode->next = newNode;
newNode->prev = newNode;
return newNode;
}

void visitURL(char* url) {


URLNode* newNode = createURLNode(url);
if (current == NULL) {
current = newNode;
} else {
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
current = newNode;
}
printf("Visited: %s\n", current->url);
}

void goBack() {
if (current == NULL) {
printf("No history available.\n");
return;
}
current = current->prev;
printf("Current URL: %s\n", current->url);
}

void displayCurrentURL() {
if (current == NULL) {
printf("No current URL.\n");
} else {
printf("Current URL: %s\n", current->url);
}
5
}

void displayMenu() {
printf("Browser History Management System\n");
printf("1. Visit URL\n");
printf("2. Go Back\n");
printf("3. Display Current URL\n");
printf("4. Exit\n");
printf("Enter your choice: ");
}

int main() {
int choice;
char url[100];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
getchar(); // to consume the newline character left by scanf
printf("Enter URL: ");
fgets(url, 100, stdin);
url[strcspn(url, "\n")] = 0; // remove newline character
visitURL(url);
break;
case 2:
goBack();
break;
case 3:
displayCurrentURL();
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

6
3. Undo-Redo Functionality using Stack
• Write a C program to implement undo and redo functionality for a simple text
editor using two stacks. The program should allow the user to type text, undo the
last operation, and redo the undone operation.
Undo-Redo Functionality using Stack
• Use two stacks to store actions for undo and redo functionality.
• Implement functions for typing text, undoing the last operation, and redoing the
undone operation.
• Use terminal input and output to interact with the user.
7
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100

typedef struct Stack {


char* data[MAX];
int top;
} Stack;

void initializeStack(Stack* stack);


int isEmpty(Stack* stack);
void push(Stack* stack, char* item);
char* pop(Stack* stack);

void typeText(Stack* undoStack, Stack* redoStack, char* text, char* editorContent);


void undo(Stack* undoStack, Stack* redoStack, char* editorContent);
void redo(Stack* undoStack, Stack* redoStack, char* editorContent);
void displayEditorContent(char* editorContent);

int main() {
Stack undoStack, redoStack;
char editorContent[MAX] = "";
int choice;
char text[MAX];

initializeStack(&undoStack);
initializeStack(&redoStack);

while (1) {
printf("\nSimple Text Editor\n");
printf("1. Type Text\n");
printf("2. Undo\n");
printf("3. Redo\n");
printf("4. Display Content\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar();

switch (choice) {
case 1:
printf("Enter text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
typeText(&undoStack, &redoStack, text, editorContent);
break;
8
case 2:
undo(&undoStack, &redoStack, editorContent);
break;
case 3:
redo(&undoStack, &redoStack, editorContent);
break;
case 4:
displayEditorContent(editorContent);
break;
case 5:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

// Stack functions
void initializeStack(Stack* stack) {
stack->top = -1;
}

int isEmpty(Stack* stack) {


return stack->top == -1;
}

void push(Stack* stack, char* item) {


if (stack->top < MAX - 1) {
stack->data[++stack->top] = strdup(item);
} else {
printf("Stack overflow\n");
}
}

char* pop(Stack* stack) {


if (!isEmpty(stack)) {
char* item = stack->data[stack->top];
stack->data[stack->top--] = NULL;
return item;
} else {
printf("Stack underflow\n");
return NULL;
}
}

void typeText(Stack* undoStack, Stack* redoStack, char* text, char* editorContent) {


9
push(undoStack, editorContent);
strcpy(editorContent, text);
initializeStack(redoStack); // Clear the redo stack
printf("Text typed successfully!\n");
}

void undo(Stack* undoStack, Stack* redoStack, char* editorContent) {


if (!isEmpty(undoStack)) {
push(redoStack, editorContent);
char* previousState = pop(undoStack);
strcpy(editorContent, previousState);
free(previousState);
printf("Undo successful!\n");
} else {
printf("Nothing to undo\n");
}
}

void redo(Stack* undoStack, Stack* redoStack, char* editorContent) {


if (!isEmpty(redoStack)) {
push(undoStack, editorContent);
char* nextState = pop(redoStack);
strcpy(editorContent, nextState);
free(nextState);
printf("Redo successful!\n");
} else {
printf("Nothing to redo\n");
}
}

void displayEditorContent(char* editorContent) {


printf("Editor Content: %s\n", editorContent);
}

OUTPUT :

10
4. Customer Service Simulation using Queue
• Develop a C program to simulate a customer service center using a queue.The
program should allow customers to enter the queue, be served in a first-come,
firstserved manner, and display the current queue. Customer Service Simulation
using Queue :
• Use a queue to manage customer requests.
• Implement functions for customers to enter the queue, be served, and display the
current queue.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Customer {


int id;
char name[100];
struct Customer* next;
} Customer;

Customer* front = NULL;


Customer* rear = NULL;
int customerCount = 0;

Customer* createCustomer(int id, char* name) {


Customer* newCustomer = (Customer*)malloc(sizeof(Customer));
newCustomer->id = id;
strcpy(newCustomer->name, name);
newCustomer->next = NULL;
11
return newCustomer;
}

void enqueueCustomer(char* name) {


Customer* newCustomer = createCustomer(++customerCount, name);
if (rear == NULL) {
front = rear = newCustomer;
} else {
rear->next = newCustomer;
rear = newCustomer;
}
printf("Customer %s (ID: %d) entered the queue.\n", name, newCustomer->id);
}

void serveCustomer() {
if (front == NULL) {
printf("No customers in the queue.\n");
return;
}
Customer* temp = front;
printf("Serving customer %s (ID: %d).\n", temp->name, temp->id);
front = front->next;
if (front == NULL) {
rear = NULL;
}
free(temp);
}

// Function to display the current queue


void displayQueue() {
if (front == NULL) {
printf("No customers in the queue.\n");
return;
}
Customer* temp = front;
printf("Current queue:\n");
while (temp != NULL) {
printf("Customer %s (ID: %d)\n", temp->name, temp->id);
temp = temp->next;
}
}

void displayMenu() {
printf("Customer Service Simulation\n");
printf("1. Enter Queue\n");
printf("2. Serve Customer\n");
printf("3. Display Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
12
}

int main() {
int choice;
char name[100];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
getchar(); // to consume the newline character left by scanf
printf("Enter customer name: ");
fgets(name, 100, stdin);
name[strcspn(name, "\n")] = 0; // remove newline character
enqueueCustomer(name);
break;
case 2:
serveCustomer();
break;
case 3:
displayQueue();
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

13
5. Task Scheduling System using Priority Queue (Min-Heap)
• Implement a C program that simulates a task scheduling system using a min-
heap. Each task should have a priority and description, and the program should
allow adding tasks, removing the highest priority task, and displaying the current
tasks. Task Scheduling System using Priority Queue (Min-Heap)
• Use a min-heap to manage tasks based on priority.
• Implement functions for adding tasks, removing the highest priority task, and
displaying current tasks.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TASKS 100

typedef struct Task {


int priority;
char description[100];
} Task;

Task heap[MAX_TASKS];
int heapSize = 0;

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

void heapifyUp(int index) {


while (index > 0 && heap[index].priority < heap[(index - 1) / 2].priority) {
swap(&heap[index], &heap[(index - 1) / 2]);
index = (index - 1) / 2;
}
}

void heapifyDown(int index) {


int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;

if (left < heapSize && heap[left].priority < heap[smallest].priority) {


smallest = left;
}
if (right < heapSize && heap[right].priority < heap[smallest].priority) {
smallest = right;
}
if (smallest != index) {
swap(&heap[index], &heap[smallest]);
heapifyDown(smallest);
}
}

// Function to add a task to the heap


void addTask(int priority, char *description) {
if (heapSize == MAX_TASKS) {
printf("Task limit reached. Cannot add more tasks.\n");
return;
}
Task newTask;
newTask.priority = priority;
strcpy(newTask.description, description);
heap[heapSize] = newTask;
heapifyUp(heapSize);
heapSize++;
printf("Task added successfully!\n");
}

void removeHighestPriorityTask() {
if (heapSize == 0) {
printf("No tasks available.\n");
return;
15
}
printf("Removing task: %s (Priority: %d)\n", heap[0].description, heap[0].priority);
heap[0] = heap[heapSize - 1];
heapSize--;
heapifyDown(0);
}

// Function to display current tasks


void displayTasks() {
if (heapSize == 0) {
printf("No tasks available.\n");
return;
}
printf("Current tasks:\n");
for (int i = 0; i < heapSize; i++) {
printf("Task: %s (Priority: %d)\n", heap[i].description, heap[i].priority);
}
}

// Function to display the menu


void displayMenu() {
printf("Task Scheduling System\n");
printf("1. Add Task\n");
printf("2. Remove Highest Priority Task\n");
printf("3. Display Tasks\n");
printf("4. Exit\n");
printf("Enter your choice: ");
}

int main() {
int choice, priority;
char description[100];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter task priority: ");
scanf("%d", &priority);
getchar(); // to consume the newline character left by scanf
printf("Enter task description: ");
fgets(description, 100, stdin);
description[strcspn(description, "\n")] = 0;
addTask(priority, description);
break;
case 2:
removeHighestPriorityTask();
break;
16
case 3:
displayTasks();
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

17
6. Social Network Friend Suggestion using Graph • Write a C program to
represent a social network using a graph and suggest friends to a user based on
mutual friends. The program should allow adding users, adding friendships, and
displaying friend suggestions for a given user using BFS.
Social Network Friend Suggestion using Graph
• Use an adjacency list to represent the social network graph.
• Implement functions for adding users, adding friendships, and displaying friend
suggestions using BFS.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_USERS 100

typedef struct Node {


int userId;
struct Node* next;
} Node;

typedef struct Graph {


int numUsers;
Node* adjLists[MAX_USERS];
char userNames[MAX_USERS][100];
} Graph;

Graph* createGraph() {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numUsers = 0;
for (int i = 0; i < MAX_USERS; i++) {
graph->adjLists[i] = NULL;
}
return graph;
}

void addUser(Graph* graph, char* userName) {


if (graph->numUsers == MAX_USERS) {
printf("User limit reached. Cannot add more users.\n");
return;
}
strcpy(graph->userNames[graph->numUsers], userName);
graph->numUsers++;
printf("User %s added successfully!\n", userName);
}

18
void addFriendship(Graph* graph, int userId1, int userId2) {
if (userId1 >= graph->numUsers || userId2 >= graph->numUsers) {
printf("Invalid user IDs. Friendship not added.\n");
return;
}
Node* newNode1 = (Node*)malloc(sizeof(Node));
newNode1->userId = userId2;
newNode1->next = graph->adjLists[userId1];
graph->adjLists[userId1] = newNode1;

Node* newNode2 = (Node*)malloc(sizeof(Node));


newNode2->userId = userId1;
newNode2->next = graph->adjLists[userId2];
graph->adjLists[userId2] = newNode2;

printf("Friendship added between %s and %s!\n", graph->userNames[userId1],


graph->userNames[userId2]);
}

void displayFriendSuggestions(Graph* graph, int userId) {


if (userId >= graph->numUsers) {
printf("Invalid user ID.\n");
return;
}

int visited[MAX_USERS] = {0};


int mutualFriends[MAX_USERS] = {0};
Node* queue[MAX_USERS];
int front = 0, rear = 0;

visited[userId] = 1;
queue[rear++] = graph->adjLists[userId];

while (front != rear) {


Node* current = queue[front++];
while (current) {
if (!visited[current->userId]) {
visited[current->userId] = 1;
Node* temp = graph->adjLists[current->userId];
while (temp) {
if (temp->userId != userId) {
mutualFriends[temp->userId]++;
}
temp = temp->next;
}
queue[rear++] = graph->adjLists[current->userId];
}
current = current->next;
19
}
}

printf("Friend suggestions for %s:\n", graph->userNames[userId]);


for (int i = 0; i < graph->numUsers; i++) {
if (i != userId && mutualFriends[i] > 0) {
printf("%s (Mutual Friends: %d)\n", graph->userNames[i], mutualFriends[i]);
}
}
}

void displayMenu() {
printf("Social Network Friend Suggestion System\n");
printf("1. Add User\n");
printf("2. Add Friendship\n");
printf("3. Display Friend Suggestions\n");
printf("4. Exit\n");
printf("Enter your choice: ");
}

int main() {
Graph* graph = createGraph();
int choice, userId1, userId2;
char userName[100];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
getchar(); // to consume the newline character left by scanf
printf("Enter user name: ");
fgets(userName, 100, stdin);
userName[strcspn(userName, "\n")] = 0;
addUser(graph, userName);
break;
case 2:
printf("Enter first user ID: ");
scanf("%d", &userId1);
printf("Enter second user ID: ");
scanf("%d", &userId2);
addFriendship(graph, userId1, userId2);
break;
case 3:
printf("Enter user ID for friend suggestions: ");
scanf("%d", &userId1);
displayFriendSuggestions(graph, userId1);
break;
case 4:
20
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

21
7. File System Simulation using Tree:
• Develop a C program to simulate a simple file system using a tree. The program
should allow creating directories and files, navigating between directories, and
displaying the structure of the current directory.
File System Simulation using Tree
• Use a tree structure to represent directories and files.
• Implement functions for creating directories and files, navigating between
directories, and displaying the current directory structure.
• Use terminal input and output to interact with the user
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME 100

typedef enum { DIRECTORY, FILE } NodeType;

typedef struct Node {


char name[MAX_NAME];
NodeType type;
struct Node* parent;
struct Node* child;
struct Node* sibling;
} Node;

Node* createNode(char* name, NodeType type) {


Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->name, name);
newNode->type = type;
newNode->parent = NULL;
newNode->child = NULL;
newNode->sibling = NULL;
return newNode;
}

Node* root;
Node* currentDirectory;

void initializeFileSystem() {
root = createNode("root", DIRECTORY);
currentDirectory = root;
}

void createDirectory(char* name) {

22
Node* newNode = createNode(name, DIRECTORY);
newNode->parent = currentDirectory;
if (currentDirectory->child == NULL) {
currentDirectory->child = newNode;
} else {
Node* temp = currentDirectory->child;
while (temp->sibling != NULL) {
temp = temp->sibling;
}
temp->sibling = newNode;
}
printf("Directory %s created.\n", name);
}

void createFile(char* name) {


Node* newNode = createNode(name, FILE);
newNode->parent = currentDirectory;
if (currentDirectory->child == NULL) {
currentDirectory->child = newNode;
} else {
Node* temp = currentDirectory->child;
while (temp->sibling != NULL) {
temp = temp->sibling;
}
temp->sibling = newNode;
}
printf("File %s created.\n", name);
}

void changeDirectory(char* name) {


if (strcmp(name, "..") == 0) {
if (currentDirectory->parent != NULL) {
currentDirectory = currentDirectory->parent;
}
} else {
Node* temp = currentDirectory->child;
while (temp != NULL) {
if (temp->type == DIRECTORY && strcmp(temp->name, name) == 0) {
currentDirectory = temp;
return;
}
temp = temp->sibling;
}
printf("Directory %s not found.\n", name);
}
}

void displayStructure(Node* node, int depth) {


for (int i = 0; i < depth; i++) {
23
printf(" ");
}
printf("%s\n", node->name);
Node* temp = node->child;
while (temp != NULL) {
displayStructure(temp, depth + 1);
temp = temp->sibling;
}
}

void displayCurrentDirectoryStructure() {
printf("Current directory: %s\n", currentDirectory->name);
displayStructure(currentDirectory, 0);
}

void displayMenu() {
printf("File System Simulation\n");
printf("1. Create Directory\n");
printf("2. Create File\n");
printf("3. Change Directory\n");
printf("4. Display Current Directory Structure\n");
printf("5. Exit\n");
printf("Enter your choice: ");
}

int main() {
initializeFileSystem();
int choice;
char name[MAX_NAME];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter directory name: ");
scanf("%s", name);
createDirectory(name);
break;
case 2:
printf("Enter file name: ");
scanf("%s", name);
createFile(name);
break;
case 3:
printf("Enter directory name (.. for parent directory): ");
scanf("%s", name);
changeDirectory(name);
break;
24
case 4:
displayCurrentDirectoryStructure();
break;
case 5:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

25
8. Spell Checker using Hash Table
• Implement a C program to create a spell checker using a hash table. The program
should read a dictionary of words into a hash table and allow the user to check if a
given word is spelled correctly.
Spell Checker using Hash Table
• Use a hash table to store dictionary words.
• Implement functions to read words into the hash table and check the spelling of
given words.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define TABLE_SIZE 1000


#define WORD_SIZE 100

typedef struct Node {


char word[WORD_SIZE];
struct Node* next;
} Node;

Node* hashTable[TABLE_SIZE];

void toLowerCase(char* str) {


for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}

unsigned int hash(char* word) {


unsigned int hashValue = 0;
for (int i = 0; word[i]; i++) {
hashValue = 31 * hashValue + word[i];
}
return hashValue % TABLE_SIZE;
}

void insert(char* word) {


toLowerCase(word);
unsigned int index = hash(word);
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->word, word);
newNode->next = hashTable[index];
hashTable[index] = newNode;

26
}

int checkWord(char* word) {


toLowerCase(word);
unsigned int index = hash(word);
Node* temp = hashTable[index];
while (temp) {
if (strcmp(temp->word, word) == 0) {
return 1;
}
temp = temp->next;
}
return 0;
}

void loadDictionary(char* filename) {


FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s\n", filename);
return;
}

char word[WORD_SIZE];
while (fscanf(file, "%s", word) != EOF) {
insert(word);
}
fclose(file);
printf("Dictionary loaded successfully!\n");
}
void displayMenu() {
printf("Spell Checker\n");
printf("1. Load Dictionary\n");
printf("2. Check Word\n");
printf("3. Exit\n");
printf("Enter your choice: ");
}

int main() {
int choice;
char word[WORD_SIZE];
char filename[WORD_SIZE];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter dictionary filename: ");
scanf("%s", filename);
27
loadDictionary(filename);
break;
case 2:
printf("Enter word to check: ");
scanf("%s", word);
if (checkWord(word)) {
printf("%s is spelled correctly.\n", word);
} else {
printf("%s is misspelled.\n", word);
}
break;
case 3:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

9. Railway Reservation System using Queue and Linked List:


• Write a C program to simulate a railway reservation system using a queue for
booking requests and a linked list to store passenger details. The program should
allow booking tickets, canceling tickets, and displaying the current reservations.
Railway Reservation System using Queue and Linked List
28
• Use a queue to manage booking requests and a linked list to store passenger
details
. • Implement functions for booking tickets, canceling tickets, and displaying current
reservations.
• Use terminal input and output to interact with the user
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NAME_SIZE 100

typedef struct Passenger {


int ticketNumber;
char name[NAME_SIZE];
struct Passenger* next;
} Passenger;

typedef struct BookingRequest {


char name[NAME_SIZE];
struct BookingRequest* next;
} BookingRequest;

Passenger* passengerList = NULL;


BookingRequest* bookingQueueFront = NULL;
BookingRequest* bookingQueueRear = NULL;
int nextTicketNumber = 1;

void enqueueBookingRequest(char* name) {


BookingRequest* newRequest =
(BookingRequest*)malloc(sizeof(BookingRequest));
strcpy(newRequest->name, name);
newRequest->next = NULL;
if (bookingQueueRear == NULL) {
bookingQueueFront = bookingQueueRear = newRequest;
} else {
bookingQueueRear->next = newRequest;
bookingQueueRear = newRequest;
}
printf("Booking request for %s added to the queue.\n", name);
}

BookingRequest* dequeueBookingRequest() {
if (bookingQueueFront == NULL) {
return NULL;
}
BookingRequest* temp = bookingQueueFront;
bookingQueueFront = bookingQueueFront->next;
29
if (bookingQueueFront == NULL) {
bookingQueueRear = NULL;
}
return temp;
}

void bookTicket() {
BookingRequest* request = dequeueBookingRequest();
if (request == NULL) {
printf("No booking requests in the queue.\n");
return;
}

Passenger* newPassenger = (Passenger*)malloc(sizeof(Passenger));


newPassenger->ticketNumber = nextTicketNumber++;
strcpy(newPassenger->name, request->name);
newPassenger->next = passengerList;
passengerList = newPassenger;

free(request);

printf("Ticket booked for %s. Ticket Number: %d\n", newPassenger->name,


newPassenger->ticketNumber);
}

// Function to cancel a ticket


void cancelTicket(int ticketNumber) {
Passenger* temp = passengerList;
Passenger* prev = NULL;

while (temp != NULL && temp->ticketNumber != ticketNumber) {


prev = temp;
temp = temp->next;
}

if (temp == NULL) {
printf("Ticket number %d not found.\n", ticketNumber);
return;
}

if (prev == NULL) {
passengerList = temp->next;
} else {
prev->next = temp->next;
}

free(temp);

printf("Ticket number %d canceled.\n", ticketNumber);


30
}

void displayReservations() {
Passenger* temp = passengerList;
if (temp == NULL) {
printf("No current reservations.\n");
return;
}
printf("Current Reservations:\n");
while (temp != NULL) {
printf("Ticket Number: %d, Name: %s\n", temp->ticketNumber, temp->name);
temp = temp->next;
}
}

void displayMenu() {
printf("Railway Reservation System\n");
printf("1. Add Booking Request\n");
printf("2. Book Ticket\n");
printf("3. Cancel Ticket\n");
printf("4. Display Current Reservations\n");
printf("5. Exit\n");
printf("Enter your choice: ");
}

int main() {
int choice, ticketNumber;
char name[NAME_SIZE];

while (1) {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter passenger name: ");
scanf("%s", name);
enqueueBookingRequest(name);
break;
case 2:
bookTicket();
break;
case 3:
printf("Enter ticket number to cancel: ");
scanf("%d", &ticketNumber);
cancelTicket(ticketNumber);
break;
case 4:
displayReservations();
break;
31
case 5:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

OUTPUT :

32
10.ATM Operations using Stack
• Develop a C program to simulate ATM operations using a stack. The program
should allow users to withdraw money, deposit money, and check the balance. It
should also support undoing the last transaction.
ATM Operations using Stack
• Use a stack to manage ATM transactions.
• Implement functions for withdrawing money, depositing money, checking the
balance, and undoing the last transaction.
• Use terminal input and output to interact with the user.
A)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

// Transaction structure
typedef struct Transaction {
char type[10];
int amount;
} Transaction;

// Stack structure
typedef struct Stack {
Transaction data[MAX];
int top;
} Stack;

void initializeStack(Stack* stack);


int isEmpty(Stack* stack);
void push(Stack* stack, Transaction transaction);
Transaction pop(Stack* stack);
void withdraw(Stack* transactionStack, int* balance, int amount);
void deposit(Stack* transactionStack, int* balance, int amount);
void checkBalance(int balance);
void undo(Stack* transactionStack, int* balance);

int main() {
Stack transactionStack;
int balance = 0;
int choice, amount;

initializeStack(&transactionStack);

while (1) {
printf("\nATM Operations\n");
printf("1. Withdraw Money\n");

33
printf("2. Deposit Money\n");
printf("3. Check Balance\n");
printf("4. Undo Last Transaction\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter amount to withdraw: ");
scanf("%d", &amount);
withdraw(&transactionStack, &balance, amount);
break;
case 2:
printf("Enter amount to deposit: ");
scanf("%d", &amount);
deposit(&transactionStack, &balance, amount);
break;
case 3:
checkBalance(balance);
break;
case 4:
undo(&transactionStack, &balance);
break;
case 5:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}

void initializeStack(Stack* stack) {


stack->top = -1;
}

int isEmpty(Stack* stack) {


return stack->top == -1;
}

void push(Stack* stack, Transaction transaction) {


if (stack->top < MAX - 1) {
stack->data[++stack->top] = transaction;
} else {
printf("Stack overflow\n");
}
34
}

Transaction pop(Stack* stack) {


if (!isEmpty(stack)) {
return stack->data[stack->top--];
} else {
printf("Stack underflow\n");
Transaction emptyTransaction = {"", 0};
return emptyTransaction;
}
}

void withdraw(Stack* transactionStack, int* balance, int amount) {


if (amount > *balance) {
printf("Insufficient balance\n");
} else {
Transaction transaction = {"withdraw", amount};
push(transactionStack, transaction);
*balance -= amount;
printf("Withdrawal successful! New balance: %d\n", *balance);
}
}

void deposit(Stack* transactionStack, int* balance, int amount) {


Transaction transaction = {"deposit", amount};
push(transactionStack, transaction);
*balance += amount;
printf("Deposit successful! New balance: %d\n", *balance);
}

void checkBalance(int balance) {


printf("Current balance: %d\n", balance);
}

void undo(Stack* transactionStack, int* balance) {


if (isEmpty(transactionStack)) {
printf("No transactions to undo\n");
} else {
Transaction lastTransaction = pop(transactionStack);
if (strcmp(lastTransaction.type, "withdraw") == 0) {
*balance += lastTransaction.amount;
printf("Undo withdrawal of %d successful! New balance: %d\n",
lastTransaction.amount, *balance);
} else if (strcmp(lastTransaction.type, "deposit") == 0) {
*balance -= lastTransaction.amount;
printf("Undo deposit of %d successful! New balance: %d\n",
lastTransaction.amount, *balance);
}
}
35
}

OUTPUT :

36

You might also like