Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Lab Manual of C Answers

The document provides algorithms and C programs for various array, string, and matrix manipulation tasks. It includes algorithms and programs to: 1. Find the sum of n numbers by prompting the user to enter numbers and using a for loop to calculate the sum. 2. Perform operations on arrays like insertion, deletion, and search by using a menu-driven program with a switch statement to call the relevant operation. 3. Multiply two matrices by initializing result and input matrices, checking if multiplication is possible, and using nested for loops to calculate each element of the result matrix. 4. Perform string operations like length, reverse, and concatenate by getting user input, displaying a menu, and implementing the selected

Uploaded by

Keshav Mathur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Lab Manual of C Answers

The document provides algorithms and C programs for various array, string, and matrix manipulation tasks. It includes algorithms and programs to: 1. Find the sum of n numbers by prompting the user to enter numbers and using a for loop to calculate the sum. 2. Perform operations on arrays like insertion, deletion, and search by using a menu-driven program with a switch statement to call the relevant operation. 3. Multiply two matrices by initializing result and input matrices, checking if multiplication is possible, and using nested for loops to calculate each element of the result matrix. 4. Perform string operations like length, reverse, and concatenate by getting user input, displaying a menu, and implementing the selected

Uploaded by

Keshav Mathur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Lab Manual of c :

2. Iterative structure ( for… While…) :-


Q.2 (ii) To write a C Program to Find Sum of n Numbers.
Ans. Algorithm:
1. Start
2. Declare variables n, i, and sum.
3. Initialize sum to 0.
4. Ask the user to enter the value of n.
5. If n is less than or equal to 0, display an error message and exit.
6. Use a loop from i = 1 to i <= n: a. Ask the user to enter the i-th number and store it in
a variable number. b. Add number to sum.
7. Display the sum of the n numbers.
8. End
Program :
#include <stdio.h>
#include <conio.h>

int main() {
int n, i;
double sum = 0.0;

printf("Enter the value of n: ");


scanf("%d", &n);

if (n <= 0) {
printf("Please enter a positive integer for n.\n");
return 1;
}

for (i = 1; i <= n; i++) {


double number;
printf("Enter number %d: ", i);
scanf("%lf", &number);
sum += number;
}
printf("The sum of the %d numbers is: %lf\n", n, sum);
return 0; // Return 0 to indicate successful execution
}
===================================
3. Array Manipulation :
Q1. Write a Program for Array Manipulation
Algorithm:
1. Start
2. Declare an array of a fixed size (e.g., arr[100]) and variables for tracking
the array size (size), the element to be inserted (element), the position
of insertion (position), and the element to be deleted (deleteElement).
3. Initialize the size to 0 to represent an empty array.
4. Display a menu to the user with options for array manipulation
operations (e.g., insert, delete, search).
5. Let the user choose an operation: a. If the user chooses to insert an
element: i. Ask the user for the element to be inserted (element) and
the position at which it should be inserted (position).
ii. Shift elements to the right to make space for the new element
and insert it at the specified position.
iii. Increment the size of the array by 1. b. If the user chooses to
delete an element:
i. Ask the user for the element to be deleted (deleteElement).
ii. Search for the element in the array and remove it if found. Shift
elements to the left to fill the gap.
iii. Decrement the size of the array by 1. c. If the user chooses to
search for an element:
i. Ask the user for the element to search (searchElement).
ii. Search for the element in the array and display its position if
found; otherwise, display a "not found" message. d. If the user chooses
to exit, end the program. e. If the user makes an invalid choice, display
an error message and show the menu again.
6. Repeat steps 5 as long as the user does not choose to exit.
7. End
Programm :
#include <stdio.h>
int main() {
int arr[100];
int size = 0;

while (1) {
int choice;
printf("Array Manipulation Menu:\n");
printf("1. Insert an element\n");
printf("2. Delete an element\n");
printf("3. Search for an element\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
if (size < 100) {
int element, position;
printf("Enter the element to insert: ");
scanf("%d", &element);
printf("Enter the position to insert (0 to %d): ", size);
scanf("%d", &position);
if (position < 0 || position > size) {
printf("Invalid position. Element not inserted.\n");
} else {
for (int i = size; i > position; i--) {
arr[i] = arr[i - 1];
}
arr[position] = element;
size++;
printf("Element %d inserted at position %d.\n",
element, position);
}
} else {
printf("Array is full. Cannot insert more elements.\n");
}
break;

case 2:
// Delete an element
if (size > 0) {
int deleteElement;
printf("Enter the element to delete: ");
scanf("%d", &deleteElement);
int found = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == deleteElement) {
for (int j = i; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
size--;
found = 1;
printf("Element %d deleted.\n", deleteElement);
break;
}
}
if (!found) {
printf("Element not found in the array.\n");
}
} else {
printf("Array is empty. Cannot delete elements.\n");
}
break;

case 3:
// Search for an element
if (size > 0) {
int searchElement;
printf("Enter the element to search: ");
scanf("%d", &searchElement);
int found = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == searchElement) {
printf("Element %d found at position %d.\n",
searchElement, i);
found = 1;
break;
}
}
if (!found) {
printf("Element %d not found in the array.\n",
searchElement);
}
} else {
printf("Array is empty. Cannot search for elements.\n");
}
break;

case 4:
// Exit
return 0;
default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
==========================
Q.2 Write a Program for Matrix Multiplication.
Algorithm:
1. Start
2. Declare variables for the number of rows and columns of the
first matrix (A), the number of rows and columns of the second
matrix (B), and the resulting matrix (C).
3. Initialize the dimensions of A and B.
4. If the number of columns in A is not equal to the number of
rows in B, display an error message and exit.
5. Declare and initialize three nested loops to iterate over rows
and columns of matrices A, B, and C.
6. Multiply the corresponding elements of A and B and
accumulate the result in the corresponding element of C.
7. Continue looping until all elements of C are computed.
8. Display the resulting matrix C.
9. End
Programm :
#include <stdio.h>

int main() {
int A[10][10], B[10][10], C[10][10];
int rowA, colA, rowB, colB;
// Input the dimensions of the matrices
printf("Enter the number of rows and columns for matrix A: ");
scanf("%d %d", &rowA, &colA);
printf("Enter the number of rows and columns for matrix B: ");
scanf("%d %d", &rowB, &colB);

// Check if matrix multiplication is possible


if (colA != rowB) {
printf("Matrix multiplication is not possible. The number of
columns in A must equal the number of rows in B.\n");
return 1; // Exit with an error code
}

// Input elements for matrix A


printf("Enter elements for matrix A:\n");
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colA; j++) {
scanf("%d", &A[i][j]);
}
}

// Input elements for matrix B


printf("Enter elements for matrix B:\n");
for (int i = 0; i < rowB; i++) {
for (int j = 0; j < colB; j++) {
scanf("%d", &B[i][j]);
}
}

// Initialize the result matrix C


for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colB; j++) {
C[i][j] = 0;
}
}

// Perform matrix multiplication


for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colB; j++) {
for (int k = 0; k < colA; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

// Display the result matrix C


printf("Resultant matrix C after multiplication:\n");
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colB; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}

return 0; // Return 0 to indicate successful execution


}
================================
4. String manipulation :
Q.1 Write a Program for String manipulation
Ans. Algorithm:
1. Start
2. Declare an array of characters (string) for storing the input string and other variables
as needed.
3. Input a string from the user.
4. Display a menu with options for string manipulation operations (e.g., length, reverse,
concatenation).
5. Let the user choose an operation: a. If the user chooses to find the length of the string,
calculate and display the length. b. If the user chooses to reverse the string, reverse the
string and display the result. c. If the user chooses to concatenate two strings, input a
second string, concatenate the two strings, and display the result. d. If the user
chooses to exit, end the program. e. If the user makes an invalid choice, display an
error message and show the menu again.
6. Repeat step 5 as long as the user does not choose to exit.
7. End
Programm :
#include <stdio.h>
#include <conio.h>
#include <string.h>

void reverseString(char str[]) {


int length = strlen(str);
int i, j;
char temp;

for (i = 0, j = length - 1; i < j; i++, j--) {


temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}

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

printf("Enter a string: ");


gets(str);
while (1) {
printf("\nString Manipulation Menu:\n");
printf("1. Find the length of the string\n");
printf("2. Reverse the string\n");
printf("3. Concatenate two strings\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Find the length of the string
printf("Length of the string: %d\n", strlen(str));
break;

case 2:
// Reverse the string
reverseString(str);
printf("Reversed string: %s\n", str);
break;

case 3:
// Concatenate two strings
char secondStr[100];
printf("Enter the second string: ");
getchar(); // Clear the newline character from the input
buffer
gets(secondStr);
strcat(str, secondStr);
printf("Concatenated string: %s\n", str);
break;

case 4:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
================================
5. Structures :
Q.1 Write a Program using structures
Ans. Algorithm:
1. Start
2. Define a structure to represent a student with attributes like name, roll number, and
marks.
3. Declare an array of structures to store multiple student records.
4. Input the number of students from the user.
5. For each student: a. Input their name, roll number, and marks. b. Store these details in
the array of structures.
6. Display a menu with options for operations (e.g., display student details, find the
average marks).
7. Let the user choose an operation: a. If the user chooses to display student details: i.
Input a roll number. ii. Search for the student with the matching roll number and
display their details. b. If the user chooses to find the average marks, calculate and
display the average marks of all students. c. If the user chooses to exit, end the
program. d. If the user makes an invalid choice, display an error message and show
the menu again.
8. Repeat step 7 as long as the user does not choose to exit.
9. End
Programm :
#include <stdio.h>
#include <conio.h>
#include <string.h>

struct Student {
char name[50];
int rollNumber;
float marks;
};

int main() {
struct Student students[100];
int numStudents;

printf("Enter the number of students: ");


scanf("%d", &numStudents);

for (int i = 0; i < numStudents; i++) {


printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
fflush(stdin); // Clear the input buffer
gets(students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Marks: ");
scanf("%f", &students[i].marks);
}

while (1) {
printf("\nStudent Information Menu:\n");
printf("1. Display student details\n");
printf("2. Find the average marks\n");
printf("3. Exit\n");
printf("Enter your choice: ");
int choice;
scanf("%d", &choice);

switch (choice) {
case 1:
// Display student details
int rollToSearch;
printf("Enter the roll number to search: ");
scanf("%d");

int found = 0;
for (int i = 0; i < numStudents; i++) {
if (students[i].rollNumber == rollToSearch) {
printf("Student Details:\n");
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Marks: %.2f\n", students[i].marks);
found = 1;
break;
}
}

if (!found) {
printf("Student with roll number %d not found.\n",
rollToSearch);
}
break;

case 2:
// Find the average marks
float totalMarks = 0;
for (int i = 0; i < numStudents; i++) {
totalMarks += students[i].marks;
}
float averageMarks = totalMarks / numStudents;
printf("Average Marks: %.2f\n", averageMarks);
break;

case 3:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
===================================
6. Stack :
Q.1 Write a Program for Stack
Ans. Algorithm:
1. Start
2. Define a stack structure with an array to store elements and a top index to keep track
of the top of the stack.
3. Initialize the stack, including the top index, to -1 to indicate an empty stack.
4. Display a menu with options for stack operations (e.g., push, pop, display, check if the
stack is empty).
5. Let the user choose an operation: a. If the user chooses to push an element onto the
stack: i. Check if the stack is full (top index equals the maximum stack size - 1). If it
is, display a "Stack Overflow" message. ii. If not, input an element and push it onto
the stack. Increment the top index. b. If the user chooses to pop an element from the
stack: i. Check if the stack is empty (top index equals -1). If it is, display a "Stack
Underflow" message. ii. If not, pop the top element from the stack. Decrement the top
index. c. If the user chooses to display the elements in the stack, iterate through the
elements and display them from the top to the bottom. d. If the user chooses to check
if the stack is empty, display "Stack is empty" if the top index is -1; otherwise, display
"Stack is not empty." e. If the user chooses to exit, end the program. f. If the user
makes an invalid choice, display an error message and show the menu again.
6. Repeat step 5 as long as the user does not choose to exit.
7. End
Programm :
#include <stdio.h>
#include <conio.h>

#define MAX_STACK_SIZE 100

struct Stack {
int items[MAX_STACK_SIZE];
int top;
};

void initializeStack(struct Stack *stack) {


stack->top = -1;
}

int isFull(struct Stack *stack) {


return stack->top == MAX_STACK_SIZE - 1;
}

int isEmpty(struct Stack *stack) {


return stack->top == -1;
}

void push(struct Stack *stack, int value) {


if (isFull(stack)) {
printf("Stack Overflow! Cannot push more elements.\n");
} else {
stack->items[++stack->top] = value;
}
}

int pop(struct Stack *stack) {


if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1;
} else {
return stack->items[stack->top--];
}
}

void display(struct Stack *stack) {


if (isEmpty(stack)) {
printf("Stack is empty.\n");
} else {
printf("Stack elements from top to bottom:\n");
for (int i = stack->top; i >= 0; i--) {
printf("%d\n", stack->items[i]);
}
}
}

int main() {
struct Stack stack;
initializeStack(&stack);
int choice, value;
while (1) {
printf("\nStack Operations Menu:\n");
printf("1. Push an element onto the stack\n");
printf("2. Pop an element from the stack\n");
printf("3. Display the stack\n");
printf("4. Check if the stack is empty\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Push an element onto the stack
printf("Enter the element to push: ");
scanf("%d", &value);
push(&stack, value);
break;

case 2:
// Pop an element from the stack
pop(&stack);
break;

case 3:
// Display the stack
display(&stack);
break;

case 4:
// Check if the stack is empty
if (isEmpty(&stack)) {
printf("Stack is empty.\n");
} else {
printf("Stack is not empty.\n");
}
break;

case 5:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
=================================
7. Stack using Linked lists :
Q.1 Write a Program to Implement Stack using Linked lists use it to convert infix expression
to postfix expression
Ans. Algorithm:
1. Start
2. Define a structure for a stack node with data and a pointer to the next node.
3. Define a stack structure with a pointer to the top node.
4. Create a function to initialize the stack (set the top pointer to NULL).
5. Create functions to push and pop nodes onto and from the stack.
6. Create a function to determine the precedence of operators.
7. Initialize an empty string for the postfix expression.
8. Create a loop to scan the infix expression from left to right.
9. For each character: a. If it's an operand, add it to the postfix expression. b. If it's an
operator, pop and append operators with higher or equal precedence from the stack to
the postfix expression, and then push the current operator onto the stack. c. If it's an
opening parenthesis '(', push it onto the stack. d. If it's a closing parenthesis ')', pop
and append operators from the stack to the postfix expression until an opening
parenthesis is encountered.
10. Continue the loop until the end of the infix expression.
11. After the loop, pop and append any remaining operators from the stack to the postfix
expression.
12. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

// Stack node structure


struct Node {
char data;
struct Node* next;
};

// Stack structure
struct Stack {
struct Node* top;
};

// Function to initialize the stack


void initializeStack(struct Stack* stack) {
stack->top = NULL;
}

// Function to push a character onto the stack


void push(struct Stack* stack, char data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

// Function to pop a character from the stack


char pop(struct Stack* stack) {
if (stack->top == NULL) {
return '\0'; // Return null character for an empty stack
}
struct Node* temp = stack->top;
char data = temp->data;
stack->top = temp->next;
free(temp);
return data;
}

// Function to determine the precedence of operators


int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
}
return 0;
}

// Function to convert infix to postfix expression


void infixToPostfix(char* infix, char* postfix) {
struct Stack stack;
initializeStack(&stack);
int i, j;
char c;
for (i = 0, j = 0; infix[i] != '\0'; i++) {
c = infix[i];

if (isalnum(c)) {
postfix[j++] = c; // Operand, add to postfix
} else if (c == '(') {
push(&stack, c);
} else if (c == ')') {
while (stack.top != NULL && stack.top->data != '(') {
postfix[j++] = pop(&stack);
}
pop(&stack); // Pop the opening parenthesis
} else {
while (stack.top != NULL && precedence(c) <=
precedence(stack.top->data)) {
postfix[j++] = pop(&stack);
}
push(&stack, c);
}
}

while (stack.top != NULL) {


postfix[j++] = pop(&stack);
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}

int main() {
char infix[100], postfix[100];
printf("Enter an infix expression: ");
gets(infix);

infixToPostfix(infix, postfix);

printf("Postfix expression: %s\n", postfix);

return 0;
}
==================================
8. Queue using pointers :
Q.1 Write a Program for Queue using pointers
Ans. Algorithm :
1. Start
2. Define a structure for a queue node that contains data and a pointer to the next node.
3. Define a queue structure with pointers to the front (head) and rear (tail) of the queue.
4. Create a function to initialize the queue (set both front and rear pointers to NULL).
5. Create a function to check if the queue is empty (front and rear are both NULL).
6. Create a function to enqueue (push) an element at the rear of the queue: a. Create a
new node with the given data. b. If the queue is empty, set both front and rear to the
new node. c. Otherwise, link the current rear node to the new node and update the rear
pointer.
7. Create a function to dequeue (pop) an element from the front of the queue: a. If the
queue is empty, return an error value (e.g., -1). b. Otherwise, remove the front node
and update the front pointer.
8. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

// Queue node structure


struct Node {
int data;
struct Node* next;
};

// Queue structure
struct Queue {
struct Node* front;
struct Node* rear;
};

// Function to initialize the queue


void initializeQueue(struct Queue* queue) {
queue->front = NULL;
queue->rear = NULL;
}

// Function to check if the queue is empty


int isEmpty(struct Queue* queue) {
return (queue->front == NULL);
}

// Function to enqueue an element at the rear of the queue


void enqueue(struct Queue* queue, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = data;
newNode->next = NULL;

if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}

// Function to dequeue an element from the front of the queue


int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
return -1; // Return -1 to indicate an empty queue
}

int data = queue->front->data;


struct Node* temp = queue->front;

if (queue->front == queue->rear) {
queue->front = NULL;
queue->rear = NULL;
} else {
queue->front = queue->front->next;
}

free(temp);
return data;
}

int main() {
struct Queue queue;
initializeQueue(&queue);

int choice, data;

while (1) {
printf("\nQueue Operations Menu:\n");
printf("1. Enqueue (Add element to the rear)\n");
printf("2. Dequeue (Remove element from the front)\n");
printf("3. Check if the queue is empty\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Enqueue
printf("Enter the element to enqueue: ");
scanf("%d", &data);
enqueue(&queue, data);
break;

case 2:
// Dequeue
data = dequeue(&queue);
if (data == -1) {
printf("Queue is empty. Cannot dequeue.\n");
} else {
printf("Dequeued element: %d\n", data);
}
break;

case 3:
// Check if the queue is empty
if (isEmpty(&queue)) {
printf("Queue is empty.\n");
} else {
printf("Queue is not empty.\n");
}
break;

case 4:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
======================================
9. Linked List Using Arrays :
Q.1 Write a Program for Linked List Using Arrays
Ans. Algorithm for Linked List Using Arrays:
1. Start
2. Define a structure for a node in the linked list with data and a pointer to the next node.
3. Declare an array of structures to represent the linked list nodes.
4. Create a variable to keep track of the head of the linked list (index of the first node).
5. Initialize the linked list by setting the head to -1 (indicating an empty list).
6. Create a function to add a new node at the end of the linked list: a. Find an empty slot
in the array or allocate more memory if needed. b. Set the data in the new node. c.
Link the new node to the previous node (if any) or update the head if it's the first
node.
7. Create a function to delete a node from the linked list: a. Locate the node to be deleted
by traversing the linked list. b. Update the pointers of the previous node to bypass the
node to be deleted. c. Release the memory occupied by the deleted node.
8. Create a function to display the contents of the linked list by traversing the nodes.
9. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

// Node structure for the linked list


struct Node {
int data;
int next; // Index of the next node in the array
};

int main() {
struct Node linkedList[100]; // Array of nodes
int head = -1; // Head of the linked list

int choice, data, newNodeIndex, currentIndex;

for (int i = 0; i < 100; i++) {


linkedList[i].next = -1; // Initialize all next pointers to -1
}

while (1) {
printf("\nLinked List Operations Menu:\n");
printf("1. Add a node\n");
printf("2. Delete a node\n");
printf("3. Display the linked list\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Add a node
printf("Enter data for the new node: ");
scanf("%d", &data);

// Find an empty slot in the array or allocate more memory


if needed
newNodeIndex = -1;
for (int i = 0; i < 100; i++) {
if (linkedList[i].next == -1) {
newNodeIndex = i;
break;
}
}

if (newNodeIndex == -1) {
printf("No empty slots available. Cannot add a new
node.\n");
} else {
linkedList[newNodeIndex].data = data;
linkedList[newNodeIndex].next = -1;

// Link the new node to the previous node or update the


head
if (head == -1) {
head = newNodeIndex;
} else {
currentIndex = head;
while (linkedList[currentIndex].next != -1) {
currentIndex = linkedList[currentIndex].next;
}
linkedList[currentIndex].next = newNodeIndex;
}
}
break;

case 2:
// Delete a node
printf("Enter the data of the node to delete: ");
scanf("%d", &data);

currentIndex = head;
int previousIndex = -1;

while (currentIndex != -1) {


if (linkedList[currentIndex].data == data) {
if (previousIndex != -1) {
linkedList[previousIndex].next =
linkedList[currentIndex].next;
} else {
head = linkedList[currentIndex].next;
}
linkedList[currentIndex].next = -1;
break;
}

previousIndex = currentIndex;
currentIndex = linkedList[currentIndex].next;
}

if (currentIndex == -1) {
printf("Node with data %d not found.\n", data);
}
break;
case 3:
// Display the linked list
currentIndex = head;
while (currentIndex != -1) {
printf("%d -> ", linkedList[currentIndex].data);
currentIndex = linkedList[currentIndex].next;
}
printf("NULL\n");
break;

case 4:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
=================================
10. Linked list using pointers :
Q.1 Write a Program for Linked list using pointers
Ans. Algorithm for Linked List Using Pointers:
1. Start
2. Define a structure for a node in the linked list with data and a pointer to the next node.
3. Declare a pointer to the head of the linked list (initially set to NULL).
4. Create a function to create a new node with the given data: a. Allocate memory for the
new node. b. Set the data of the new node. c. Set the next pointer of the new node to
NULL.
5. Create a function to add a new node at the end of the linked list: a. Create a new node
using the createNode function. b. If the head pointer is NULL (empty list), set the
head pointer to the new node. c. Otherwise, traverse the list to find the last node
(where next is NULL) and link the last node to the new node.
6. Create a function to delete a node with a specific value from the linked list: a. If the
head pointer is NULL, display an error message (empty list). b. If the node to delete is
the head node, update the head pointer to the next node. c. Otherwise, traverse the list
to find the node before the one to be deleted and update the next pointer to skip the
node to delete.
7. Create a function to display the contents of the linked list: a. Traverse the list from the
head and print the data of each node.
8. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

// Node structure for the linked list


struct Node {
int data;
struct Node* next;
};

// Function to create a new node with the given data


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to add a new node at the end of the linked list
void appendNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

// Function to delete a node with a specific value from the linked list
void deleteNode(struct Node** head, int data) {
if (*head == NULL) {
printf("Linked list is empty. Cannot delete.\n");
return;
}

if ((*head)->data == data) {
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}

struct Node* current = *head;


struct Node* previous = NULL;
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
}

if (current == NULL) {
printf("Node with data %d not found.\n", data);
} else {
previous->next = current->next;
free(current);
}
}

// Function to display the linked list


void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;
int choice, data;

while (1) {
printf("\nLinked List Operations Menu:\n");
printf("1. Add a node\n");
printf("2. Delete a node\n");
printf("3. Display the linked list\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
// Add a node
printf("Enter data for the new node: ");
scanf("%d", &data);
appendNode(&head, data);
break;

case 2:
// Delete a node
printf("Enter the data of the node to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;

case 3:
// Display the linked list
displayList(head);
break;

case 4:
// Exit
return 0;

default:
printf("Invalid choice. Please choose a valid option.\n");
}
}

return 0;
}
=====================================
11. Dynamic allocation operator :
Q.1 Write a Program using Dynamic allocation operator
Ans. Algorithm for Dynamic Allocation of an Array:
1. Start
2. Declare a pointer to int (int* ptr) to represent the dynamically allocated array.
3. Create a function to read the size of the array from the user.
4. Allocate memory for the array based on the user-input size using the malloc function.
5. Create a function to initialize the array elements.
6. Create a function to display the elements of the dynamically allocated array.
7. Create a function to release the dynamically allocated memory using the free
function.
8. In the main program: a. Read the size of the array from the user. b. Allocate memory
for the array. c. Initialize the array elements. d. Display the array. e. Release the
allocated memory.
9. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

// Function to read the size of the array from the user


int readSize() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
return size;
}

// Function to initialize the dynamically allocated array


void initializeArray(int* ptr, int size) {
printf("Enter %d elements for the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &ptr[i]);
}
}

// Function to display the dynamically allocated array


void displayArray(int* ptr, int size) {
printf("Array elements are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
}

int main() {
int size = readSize();
int* ptr = (int*)malloc(size * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

initializeArray(ptr, size);
displayArray(ptr, size);

free(ptr); // Release the dynamically allocated memory

return 0;
}
===================================
12. File handling :
Q.1 Write a Program to File handling
Ans. Algorithm:
1. Start
2. Create a function to write data to a file: a. Open the file in write mode using the fopen
function. b. Check if the file was opened successfully. c. Write data to the file using
fprintf or fputc. d. Close the file using fclose.
3. Create a function to read data from a file: a. Open the file in read mode using the
fopen function. b. Check if the file was opened successfully. c. Read data from the
file using fscanf or fgetc until the end of the file is reached. d. Close the file using
fclose.
4. In the main program: a. Prompt the user to choose whether to write data to a file or
read data from a file. b. If the user chooses to write: i. Enter the filename to write to.
ii. Call the function to write data to the file. c. If the user chooses to read: i. Enter the
filename to read from. ii. Call the function to read data from the file. d. Display the
contents of the file (if reading). e. End the program.
5. End
Program :
#include <stdio.h>
#include <conio.h>

// Function to write data to a file


void writeToFile(const char* filename) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening the file for writing.\n");
return;
}

printf("Enter data to write to the file (Ctrl+Z to end):\n");


int ch;
while ((ch = getche()) != 26) { // 26 is the ASCII code for Ctrl+Z (end
of file)
fputc(ch, file);
}

fclose(file);
printf("\nData written to the file successfully.\n");
}

// Function to read data from a file


void readFromFile(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening the file for reading.\n");
return;
}

printf("Contents of the file:\n");


int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}

fclose(file);
}

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

printf("File Handling Menu:\n");


printf("1. Write data to a file\n");
printf("2. Read data from a file\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if (choice == 1) {
printf("Enter the filename to write to: ");
scanf("%s", filename);
writeToFile(filename);
} else if (choice == 2) {
printf("Enter the filename to read from: ");
scanf("%s", filename);
readFromFile(filename);
} else {
printf("Invalid choice. Please choose 1 or 2.\n");
}

return 0;
}
=======================================
13. Trees :
Q.1 Write a Program for Trees
Ans. Algorithm :
1. Start
2. Define a structure for a tree node with data, left child pointer, and right child pointer.
3. Create functions to: a. Create a new tree node with the given data. b. Insert a node into
the binary tree:
 Start at the root node.
 If the tree is empty (root is NULL), create a new node as the root.
 If the data to insert is less than the current node's data, go to the left child, or
create a new node if the left child is NULL.
 If the data to insert is greater, go to the right child, or create a new node if the
right child is NULL. c. Traverse the binary tree:
 In-order: Traverse the left subtree, visit the current node, traverse the right
subtree. d. Free the memory of the entire tree.
4. In the main program: a. Create a root node (initially NULL). b. Insert nodes with data
into the binary tree. c. Traverse and display the tree using in-order traversal. d. Free
the memory occupied by the tree.
5. End
Program :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

// Structure for a tree node


struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};

// Function to create a new tree node


struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct
TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node into the binary tree


struct TreeNode* insertNode(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}

if (data < root->data) {


root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}

return root;
}

// Function to traverse and display the binary tree (in-order)


void inOrderTraversal(struct TreeNode* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}

// Function to free the memory of the entire tree


void freeTree(struct TreeNode* root) {
if (root != NULL) {
freeTree(root->left);
freeTree(root->right);
free(root);
}
}

int main() {
struct TreeNode* root = NULL;
// Insert nodes into the binary tree
root = insertNode(root, 50);
root = insertNode(root, 30);
root = insertNode(root, 70);
root = insertNode(root, 20);
root = insertNode(root, 40);

// Traverse and display the binary tree (in-order)


printf("In-order traversal of the binary tree: ");
inOrderTraversal(root);
printf("\n");

// Free the memory occupied by the tree


freeTree(root);

return 0;
}

You might also like