0% found this document useful (0 votes)
16 views46 pages

Programming Assignment - 1: Program 1

The document contains programming assignments in C, including tasks for counting words, characters, and lines in text, managing student data with search and sort functionalities, multiplying polynomials, and performing operations on sparse matrices. Each program includes source code, algorithms, and detailed steps for implementation. The assignments aim to enhance understanding of data structures, algorithms, and C programming concepts.

Uploaded by

patilchinmay510
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)
16 views46 pages

Programming Assignment - 1: Program 1

The document contains programming assignments in C, including tasks for counting words, characters, and lines in text, managing student data with search and sort functionalities, multiplying polynomials, and performing operations on sparse matrices. Each program includes source code, algorithms, and detailed steps for implementation. The assignments aim to enhance understanding of data structures, algorithms, and C programming concepts.

Uploaded by

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

PROGRAMMING ASSIGNMENT - 1

PROGRAM 1

Develop a C program to count the number of words, characters and line in a


given text.

#include <stdio.h>
#include <stdbool.h>

void countText(const char *text, int *words, int *characters, int *lines) {
*words = *characters = *lines = 0;
bool inWord = false;

for (int i = 0; text[i] != '\0'; i++) {


(*characters)++;
if (text[i] == '\n') {
(*lines)++;
}
if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t') {
inWord = false;
} else if (!inWord) {
inWord = true;
(*words)++;
}
}
if (*characters > 0 && text[*characters - 1] != '\n') {
(*lines)++; // Account for the last line if it doesn't end with a newline
}
}

int main() {
char text[1000];

printf("Enter text :\n");


fgets(text, sizeof(text), stdin);

int words, characters, lines;


countText(text, &words, &characters, &lines);
printf("Words: %d\nCharacters: %d\nLines: %d\n", words, characters, lines);
return 0;
}
ALGORITHM

1. Initialize Counters:
• Set counters for characters, words, and lines to 0.
• Define a boolean flag inWord to track whether the program is
currently inside a word.
2. Read the Input:
• Accept the input text from the user.
3. Process Each Character:
• For each character in the input:
1. Increment the characters counter.
2. If the character is a newline ('\n'), increment the lines
counter.
3. If the character is a space (' '), tab ('\t'), or newline ('\n'):
• Set inWord to false (indicating the end of a word).
4. If the character is not a space, tab, or newline, and inWord is
false:
• Increment the words counter.
• Set inWord to true (indicating the start of a word).
4. Handle the Last Line:
• If the input text does not end with a newline, increment the lines
counter to account for the last line.
5. Output the Results:
• Print the values of characters, words, and lines.

OUTPUT
PROGRAM 2

Create a structure/class for a group of 50 students holding data for their Regn
no., Name, Branch, CGPA
a) Call linear search function to display data of student with a particular Regn
no..
b) Call bubble sort function to arrange data of students according to Regn no.
c) Apply binary search on the above output (part b) to display data of a student
with a particular Regn no.
d) Use and modify Insertion sort logic to arrange data of students in
descending order of CGPA

// Student Data Management


#include <stdio.h>
#include <string.h>

#define MAX_STUDENTS 50

// Structure to hold student data


typedef struct {
int regn_no;
char name[50];
char branch[50];
float cgpa;
} Student;

// Function prototypes
void linearSearch(Student students[], int n, int regn_no);
void bubbleSort(Student students[], int n);
int binarySearch(Student students[], int n, int regn_no);
void insertionSortDescending(Student students[], int n);
void displayStudent(Student student);

// Main function
int main() {
Student students[MAX_STUDENTS];
int n;

printf("Enter the number of students (max %d): ", MAX_STUDENTS);


scanf("%d", &n);

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


printf("\nEnter details for student %d:\n", i + 1);
printf("Registration Number: ");
scanf("%d", &students[i].regn_no);
printf("Name: ");
scanf("%s", students[i].name);
printf("Branch: ");
scanf("%s", students[i].branch);
printf("CGPA: ");
scanf("%f", &students[i].cgpa);
}

int choice;
do {
printf("\nMenu:\n");
printf("1. Linear Search by Registration Number\n");
printf("2. Bubble Sort by Registration Number\n");
printf("3. Binary Search by Registration Number\n");
printf("4. Insertion Sort by CGPA (Descending)\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: {
int regn_no;
printf("Enter Registration Number to search: ");
scanf("%d", &regn_no);
linearSearch(students, n, regn_no);
break;
}
case 2:
bubbleSort(students, n);
printf("\nStudents sorted by Registration Number:\n");
for (int i = 0; i < n; i++) {
displayStudent(students[i]);
}
break;
case 3: {
int regn_no;
printf("Enter Registration Number to search: ");
scanf("%d", &regn_no);
int index = binarySearch(students, n, regn_no);
if (index != -1) {
printf("\nStudent found:\n");
displayStudent(students[index]);
} else {

printf("\nStudent not found.\n");


}
break;
}
case 4:
insertionSortDescending(students, n);
printf("\nStudents sorted by CGPA (Descending):\n");
for (int i = 0; i < n; i++) {
displayStudent(students[i]);
}
break;
case 5:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Try again.\n");
}
} while (choice != 5);

return 0;
}

// Function definitions
void linearSearch(Student students[], int n, int regn_no) {
for (int i = 0; i < n; i++) {
if (students[i].regn_no == regn_no) {
printf("\nStudent found:\n");
displayStudent(students[i]);
return;
}
}
printf("\nStudent not found.\n");
}

void bubbleSort(Student students[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (students[j].regn_no > students[j + 1].regn_no) {
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}

int binarySearch(Student students[], int n, int regn_no) {


int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (students[mid].regn_no == regn_no) {
return mid;
} else if (students[mid].regn_no < regn_no) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

void insertionSortDescending(Student students[], int n) {


for (int i = 1; i < n; i++) {
Student key = students[i];
int j = i - 1;
while (j >= 0 && students[j].cgpa < key.cgpa) {
students[j + 1] = students[j];
j--;
}
students[j + 1] = key;
}
}

void displayStudent(Student student) {


printf("Registration Number: %d\n", student.regn_no);
printf("Name: %s\n", student.name);
printf("Branch: %s\n", student.branch);
printf("CGPA: %.2f\n", student.cgpa);
}
ALGORITHM

1. Initialize Program
• Define a structure Student to hold:
• Registration number (regn_no).
• Name (name).
• Branch (branch).
• CGPA (cgpa).
• Create an array to store data for up to MAX_STUDENTS.
2. Input Student Data
• Ask the user for the number of students (n).
• For each student, input their:
• Registration number.
• Name.
• Branch.
• CGPA.
3. Menu Options
• Provide the user with the following options:
1. Linear Search by Registration Number.
2. Bubble Sort by Registration Number.
3. Binary Search by Registration Number.
4. Insertion Sort by CGPA in Descending Order.
5. Exit.

Linear Search Algorithm


1. Accept a registration number (regn_no) to search.
2. Loop through the array of students:
• If the regn_no matches a student's registration number:
• Print the student's details.
• Exit the loop.
3. If no match is found, display "Student not found."

Bubble Sort Algorithm


1. For each pass through the array:
• Compare adjacent students based on their regn_no.
• Swap them if the current student has a larger regn_no than the
next student.
2. Repeat until the array is sorted.

Binary Search Algorithm


1. Ensure the student array is sorted by regn_no (using Bubble Sort first).
2. Initialize two pointers: left = 0 and right = n - 1.
3. While left <= right:
• Compute the middle index: mid = left + (right - left) / 2.
• If students[mid].regn_no matches the search key, return the
student's details.
• If the search key is smaller, adjust the right pointer (mid - 1).
• If the search key is larger, adjust the left pointer (mid + 1).
4. If no match is found, display "Student not found."

Insertion Sort Algorithm


1. Start from the second student in the array.
2. For each student:
• Compare the current student’s CGPA with those before it.
• Shift students with lower CGPA to the right.
• Place the current student in its correct position.
3. Repeat until the array is sorted in descending order of CGPA.

Display Student Details


• For any student found or sorted, display:
• Registration number.
• Name.
• Branch.
• CGPA.

Program Termination
• Exit the program when the user selects the "Exit" option.
OUTPUT
PROGRAM 3

Develop a C program to multiply two polynomials A(x) and B(x) using arrays
and store the resultant in C(x).

#include <stdio.h>

// Function to multiply two polynomials A(x) and B(x) and store the result in
C(x)
void multiplyPolynomials(int A[], int B[], int C[], int degA, int degB) {
// Initialize all coefficients of C(x) to 0
for (int i = 0; i <= degA + degB; i++) {
C[i] = 0;
}

// Multiply each term of A(x) with each term of B(x) and add to C(x)
for (int i = 0; i <= degA; i++) {
for (int j = 0; j <= degB; j++) {
C[i + j] += A[i] * B[j];
}
}
}

int main() {
int degA, degB;

// Input the degree of polynomial A(x)


printf("Enter the degree of polynomial A(x): ");
scanf("%d", &degA);

int A[degA + 1];


printf("Enter the coefficients of A(x) (from lowest to highest degree): \n");
for (int i = 0; i <= degA; i++) {
scanf("%d", &A[i]);
}

// Input the degree of polynomial B(x)


printf("Enter the degree of polynomial B(x): ");
scanf("%d", &degB);

int B[degB + 1];


printf("Enter the coefficients of B(x) (from lowest to highest degree): \n");
for (int i = 0; i <= degB; i++) {
scanf("%d", &B[i]);
}

// Resultant polynomial C(x) will have degree degA + degB


int C[degA + degB + 1];

// Multiply the polynomials


multiplyPolynomials(A, B, C, degA, degB);

// Print the resultant polynomial C(x)


printf("The resultant polynomial C(x) is: \n");
for (int i = 0; i <= degA + degB; i++) {
printf("%d", C[i]);
if (i > 0) {
printf("x^%d", i);
}
if (i < degA + degB) {
printf(" + ");
}
}
printf("\n");

return 0;
}

ALGORITHM

1. Input the Degrees and Coefficients:


• Input the degree degA of polynomial A(x).
• Input the coefficients of A(x) as an array A[].
• Input the degree degB of polynomial B(x).
• Input the coefficients of B(x) as an array B[].
2. Initialize the Resultant Polynomial:
• Define the degree of the resultant polynomial degC=degA+degB.
• Create an array C[] of size degC+1 to store the coefficients of the
resultant polynomial.
• Initialize all elements of C[] to 0.
3. Multiply Polynomials:
• For each coefficient A[i] (from i=0 to degA):
• For each coefficient B[j] (from j=0 to degB):
• Update the coefficient of xi+j in C[]: C[i+j]=C[i+j]+
(A[i]×B[j])
4. Output the Resultant Polynomial:
• Print the coefficients of C[] from index 0 to degC, formatting them
as a polynomial expression.
OUTPUT
PROGRAM 4

Develop a C program to perform the following operations on sparse matrix


using
arrays and functions.
i. To add 2 sparse matrices
ii. To find the fast transpose of the sparse matrix

#include <stdio.h>
#define MAX 100

typedef struct {
int row;
int col;
int value;
} SparseMatrix;

// Function to add two sparse matrices


void addSparseMatrices(SparseMatrix A[], SparseMatrix B[], SparseMatrix C[])
{
int i = 1, j = 1, k = 1;
if (A[0].row != B[0].row || A[0].col != B[0].col) {
printf("Matrix dimensions do not match for addition!\n");
return;
}

C[0].row = A[0].row;
C[0].col = A[0].col;
while (i <= A[0].value && j <= B[0].value) {
if (A[i].row < B[j].row || (A[i].row == B[j].row && A[i].col < B[j].col)) {
C[k++] = A[i++];
} else if (B[j].row < A[i].row || (B[j].row == A[i].row && B[j].col < A[i].col))
{
C[k++] = B[j++];
} else {
C[k].row = A[i].row;
C[k].col = A[i].col;
C[k++].value = A[i++].value + B[j++].value;
}
}
while (i <= A[0].value) {
C[k++] = A[i++];
}
while (j <= B[0].value) {
C[k++] = B[j++];
}
C[0].value = k - 1;
}

// Function to find the fast transpose of a sparse matrix


void fastTranspose(SparseMatrix A[], SparseMatrix T[]) {
int rowTerms[MAX] = {0}, startingPos[MAX];
int i, j;

T[0].row = A[0].col;
T[0].col = A[0].row;
T[0].value = A[0].value;

// Count the number of elements in each column


for (i = 1; i <= A[0].value; i++) {
rowTerms[A[i].col]++;
}

// Calculate starting position for each column in transposed matrix


startingPos[0] = 1;
for (i = 1; i < A[0].col; i++) {
startingPos[i] = startingPos[i - 1] + rowTerms[i - 1];
}

// Place elements in transposed matrix


for (i = 1; i <= A[0].value; i++) {
j = startingPos[A[i].col]++;
T[j].row = A[i].col;
T[j].col = A[i].row;
T[j].value = A[i].value;
}
}

int main() {
SparseMatrix A[MAX], B[MAX], C[MAX], T[MAX];
int n, m, nonZeroA, nonZeroB, choice;

printf("Enter the dimensions of the first sparse matrix (rows and columns):
");
scanf("%d %d", &A[0].row, &A[0].col);

printf("Enter the number of non-zero elements in the first matrix: ");


scanf("%d", &A[0].value);
printf("Enter the elements (row, column, value):\n");
for (int i = 1; i <= A[0].value; i++) {
scanf("%d %d %d", &A[i].row, &A[i].col, &A[i].value);
}

printf("Choose an operation:\n");
printf("1. Add two sparse matrices\n2. Find the fast transpose\n");
scanf("%d", &choice);

if (choice == 1) {
printf("Enter the dimensions of the second sparse matrix (rows and
columns): ");
scanf("%d %d", &B[0].row, &B[0].col);

printf("Enter the number of non-zero elements in the second matrix: ");


scanf("%d", &B[0].value);

printf("Enter the elements (row, column, value):\n");


for (int i = 1; i <= B[0].value; i++) {
scanf("%d %d %d", &B[i].row, &B[i].col, &B[i].value);
}

addSparseMatrices(A, B, C);
printf("Resultant matrix after addition:\n");
for (int i = 0; i <= C[0].value; i++) {
printf("%d %d %d\n", C[i].row, C[i].col, C[i].value);
}
} else if (choice == 2) {
fastTranspose(A, T);
printf("Transpose of the matrix:\n");
for (int i = 0; i <= T[0].value; i++) {
printf("%d %d %d\n", T[i].row, T[i].col, T[i].value);
}
} else {
printf("Invalid choice!\n");
}

return 0;
}
ALGORITHM

1. Algorithm to Add Two Sparse Matrices

Input: Sparse matrices A and B (each represented as an array of triplets: row,


column, and value).
Output: Resultant sparse matrix C after addition.
Steps:
1. Check Compatibility:
• Ensure A and B have the same dimensions.
• If dimensions differ, print an error message and terminate the
algorithm.
2. Initialize Indices:
• Set i=1,j=1,k=1, where:
• i traverses A,
• j traverses B,
• k traverses C.
3. Traverse A and B:
• While i≤A[0].value and j≤B[0].value:
• Compare A[i].row,A[i].col with B[j].row,B[j].col:
• If A[i] precedes B[j], copy A[i] to C[k], increment i and k.
• If B[j] precedes A[i], copy B[j] to C[k], increment j and k.
• If they are equal, add their values, store in C[k], and
increment i,j,k.
4. Copy Remaining Elements:
• Copy any remaining elements from A or B to C.
5. Update Resultant Matrix:
• Set C[0].row=A[0].row, C[0].col=A[0].col, and C[0].value=k−1.
6. Output C:
• Print C.

2. Algorithm to Find the Fast Transpose of a Sparse Matrix

Input: Sparse matrix A (represented as an array of triplets).


Output: Transposed sparse matrix T.
Steps:
1. Initialize Transpose Dimensions:
• Set T[0].row=A[0].col, T[0].col=A[0].row, and
T[0].value=A[0].value.
2. Count Elements per Column:
• Create an array rowTerms initialized to 0.
• For each non-zero element in A[i], increment rowTerms[A[i].col].
3. Calculate Starting Positions:
• Create an array startingPos of size A[0].col.
• Set startingPos[0]=1.
• For each column j, set
startingPos[j]=startingPos[j−1]+rowTerms[j−1].
4. Place Elements in Transpose:
• For each non-zero element A[i]:
• Determine its position pos using startingPos[A[i].col].
• Place the element in T[pos] with transposed row and column.
• Increment startingPos[A[i].col].
5. Output T:
• Print T.

OUTPUT
PROGRAM 5

Develop a C program to count vowels and consonants in a string using pointer.

#include <stdio.h>
#include <ctype.h>

void countVowelsAndConsonants(char *str, int *vowelCount, int


*consonantCount) {
*vowelCount = 0;
*consonantCount = 0;

while (*str != '\0') {


char ch = tolower(*str); // Convert character to lowercase for comparison
if (ch >= 'a' && ch <= 'z') { // Check if character is an alphabet
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
(*vowelCount)++;
} else {
(*consonantCount)++;
}
}
str++; // Move to the next character in the string
}
}

int main() {
char str[100];
int vowels, consonants;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin); // Read input string

countVowelsAndConsonants(str, &vowels, &consonants);

printf("Number of vowels: %d\n", vowels);


printf("Number of consonants: %d\n", consonants);

return 0;
}
ALGORITHM

Algorithm to Count Vowels and Consonants in a String Using Pointers


Input: A string str.
Output: The count of vowels and consonants in the string.
Steps:
1. Initialize Counters:
• Create two variables vowelCount and consonantCount and initialize
them to 0.
2. Set Pointer:
• Create a pointer ptr and point it to the first character of the string
str.
3. Traverse the String:
• While the character pointed to by ptr is not the null terminator (\0):
• Convert the character pointed to by ptr to lowercase for case-
insensitive comparison.
4. Check Alphabet:
• If the character is an alphabet (i.e., between 'a' and 'z'):
• Vowel Check:
• If the character is one of 'a', 'e', 'i', 'o', or 'u', increment
vowelCount.
• Consonant Check:
• Otherwise, increment consonantCount.
5. Move Pointer:
• Increment ptr to point to the next character in the string.
6. Output Results:
• Print the values of vowelCount and consonantCount.

OUTPUT
PROGRAM 6

Given a stack of N integers. In one operation, you can either pop an element
from the stack or push any popped element into the stack. You need to
maximize the top element of the stack after performing exactly K operations. If
the stack becomes empty after performing K operations and there is no other
way for the stack to be non-empty, print -1.

#include <stdio.h>
#include <limits.h>

#define MAX 100

// Function to find the maximum top element after K operations


int maximizeTop(int stack[], int n, int k) {
// If no operations are allowed, return the current top element
if (k == 0) {
return stack[0];
}

// If k < n, we can pop k elements and choose the maximum


if (k < n) {
int maxTop = INT_MIN;
for (int i = 0; i < k; i++) {
if (stack[i] > maxTop) {
maxTop = stack[i];
}
}
return maxTop;
}

// If k >= n, pop all elements


if (k >= n) {
// Stack becomes empty after exactly n pops
if (k == n) {
return -1;
}
// When k > n, we can push back the maximum of the first n elements
int maxTop = INT_MIN;
for (int i = 0; i < n; i++) {
if (stack[i] > maxTop) {
maxTop = stack[i];
}
}
return maxTop;
}

return -1; // Default case (should not be reached)


}

int main() {
int stack[MAX], n, k;

printf("Enter the size of the stack: ");


scanf("%d", &n);

printf("Enter the elements of the stack (top to bottom): ");


for (int i = 0; i < n; i++) {
scanf("%d", &stack[i]);
}

printf("Enter the number of operations (K): ");


scanf("%d", &k);

int result = maximizeTop(stack, n, k);

if (result == -1) {
printf("-1\n");
} else {
printf("The maximum top element after %d operations is: %d\n", k,
result);
}

return 0;
}
ALGORITHM

1. If K = 0, return the current top of the stack if it is non-empty; otherwise


return -1.
2. If K = 1 and the stack is non-empty, pop the top element and return the
maximum of the remaining stack or -1 if empty.
3. If K >= N, return the maximum element from the stack.
4. If K < N, pop the first K elements, track the maximum element
encountered, and then:
• After popping, you can push the largest element back into the
stack.
• If K == N, it means all elements are popped, so push back the
maximum element.
• If K < N, leave the stack as it is and return the maximum element
that can be at the top.

OUTPUT
PROGRAM 7

Develop a C program to reverse a given integer number using stack.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10

// Define the stack structure


typedef struct Stack {
int arr[MAX];
int top;
} Stack;

// Initialize the stack


void initStack(Stack *stack) {
stack->top = -1;
}

// Check if the stack is empty


int isEmpty(Stack *stack) {
return stack->top == -1;
}

// Check if the stack is full


int isFull(Stack *stack) {
return stack->top == MAX - 1;
}

// Push an element onto the stack


void push(Stack *stack, int value) {
if (isFull(stack)) {
printf("Stack overflow!\n");
return;
}
stack->arr[++stack->top] = value;
}

// Pop an element from the stack


int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack underflow!\n");
return -1;
}
return stack->arr[stack->top--];
}

// Reverse the digits of an integer using a stack


int reverseNumber(int num) {
Stack stack;
initStack(&stack);

// Handle negative numbers


int isNegative = num < 0;
if (isNegative) {
num = -num;
}

// Push all digits of the number onto the stack


while (num > 0) {
push(&stack, num % 10);
num /= 10;
}

// Pop digits from the stack to construct the reversed number


int reversedNum = 0;
int multiplier = 1;
while (!isEmpty(&stack)) {
reversedNum += pop(&stack) * multiplier;
multiplier *= 10;
}

return isNegative ? -reversedNum : reversedNum;


}

int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

int reversedNumber = reverseNumber(number);


printf("Reversed number: %d\n", reversedNumber);

return 0;
}
ALGORITHM

1. Input: Read the given integer.


2. Initialize a Stack: Create a stack (it can be implemented using an array or
linked list).
3. Extract Digits:
• Extract each digit of the integer starting from the rightmost digit by
repeatedly dividing the number by 10 and pushing the remainder
(which is the last digit) onto the stack.
4. Reconstruct the Reversed Number:
• After all digits are pushed onto the stack, start popping from the
stack and reconstruct the number.
• Multiply the reversed number by 10 and add the popped digit to it
at each step.
5. Output: Print the reversed number.

OUTPUT
PROGRAM 8

Given a list, split it into two sublists — one for the front half, and one for the
back half. If the number of elements is odd, the extra element should go in the
front list. So FrontBack Split() on the list {2, 3, 5, 7, 11} should yield the two
lists {2, 3, 5} and {7, 11}.

#include <stdio.h>
#include <stdlib.h>

// Function to split the list into two sublists


void splitList(int *arr, int length) {
int mid = (length + 1) / 2; // Middle index for the front half (extra element
goes here if odd)

// Front half: elements from 0 to mid-1


printf("Front half: ");
for (int i = 0; i < mid; i++) {
printf("%d ", arr[i]);
}

// Back half: elements from mid to length-1


printf("\nBack half: ");
for (int i = mid; i < length; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {2, 3, 5, 7, 11}; // Example list
int length = sizeof(arr) / sizeof(arr[0]);

splitList(arr, length); // Calling the function to split the list

return 0;
}
ALGORITHM

Input: Given a list of integers.


Steps:
1. Calculate the middle index:
• If the length of the list is even, the middle index will divide the list
evenly.
• If the length is odd, the middle index will be the floor value of
length/2. This way, the extra element will be placed in the front
half.
2. Split the list:
• The front half will contain elements from index 0 to the middle
index (inclusive if the length is odd).
• The back half will contain the remaining elements from the middle
index + 1 to the end.
3. Return:
• Two sublists — one for the front and one for the back.

OUTPUT
PROGRAM 9

Write a C program to sort the singly linked list of integers in ascending order

#include <stdio.h>
#include <stdlib.h>

// Definition of the node structure


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

// Function to create a new node


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

// Function to insert a node at the end of the list


void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to print the list


void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to sort the linked list using Bubble Sort
void bubbleSort(struct Node* head) {
if (head == NULL) return; // List is empty, no sorting needed

int swapped;
struct Node *ptr1, *ptr2;

// Bubble sort loop


do {
swapped = 0;
ptr1 = head;

while (ptr1 != NULL && ptr1->next != NULL) {


ptr2 = ptr1->next;

// If current node's data is greater than next node's data, swap them
if (ptr1->data > ptr2->data) {
int temp = ptr1->data;
ptr1->data = ptr2->data;
ptr2->data = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
} while (swapped); // Continue sorting until no swaps are made
}

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

// Inserting nodes into the linked list


insertEnd(&head, 5);
insertEnd(&head, 2);
insertEnd(&head, 9);
insertEnd(&head, 1);
insertEnd(&head, 3);

printf("Original List: ");


printList(head);

// Sorting the linked list


bubbleSort(head);

printf("Sorted List: ");


printList(head);
return 0;

ALGORITHM

The Bubble Sort algorithm for a singly linked list consists of the following steps:
1. Initialize:
• Start with the head of the linked list.
• If the list is empty (head is NULL), there is no need to sort.
2. Outer Loop:
• Perform repeated steps until no more swaps are needed (no
elements are swapped in a full pass through the list).
• Use a flag swapped to indicate whether any nodes were swapped
during the current pass.
3. Inner Loop:
• Traverse the linked list using two pointers, ptr1 and ptr2, where
ptr1 moves through each node, and ptr2 points to the next node.
• Compare the data of ptr1 and ptr2.
• If the data of ptr1 is greater than the data of ptr2, swap their data
(exchange the values of ptr1 and ptr2).
4. Repeat the Inner Loop:
• Continue this process until you reach the end of the list (i.e., the
last node has been compared).
5. Repeat the Outer Loop:
• If any swaps were made in the current pass (swapped is True),
repeat the process to ensure the list is fully sorted.
6. Return the Sorted List:
• Once no swaps are made in a pass, the linked list is sorted.

OUTPUT
PROGRAM 10

Alice and Bob are playing a game of Blobby Volley. In this game, in each turn,
one player is the server and the other player is the receiver. Initially, Alice is
the server, and Bob is the receiver.If the server wins the point in this turn, their
score increases by 1, and they remain as the server for the next turn. But if the
receiver wins the point in this turn, their score does not increase. But they
become the server in the next turn. In other words, your score increases only
when you win a point when you are the server. Please see the Sample Inputs
and Explanation for more detailed explanation. They start with a score of 00
each, and play N turns. The winner of each of those hands is given to you as a
string consisting of 'A's and 'B's. 'A' denoting that Alice won that point, and 'B'
denoting that Bob won that point. Your job is the find the score of both of them
after the N turns.

#include <stdio.h>
#include <string.h>

int main() {
int alice_score = 0, bob_score = 0;
char server = 'A'; // Alice starts as the server
char result[101]; // Array to hold the result string (max 100 turns)

// Input the result of the turns


printf("Enter the result of the turns (a string of 'A's and 'B's): ");
scanf("%s", result);

// Length of the result string


int n = strlen(result);

// Process each turn


for (int i = 0; i < n; i++) {
if (result[i] == server) {
// Server wins, increase the server's score
if (server == 'A') {
alice_score++;
} else {
bob_score++;
}
} else {
// Receiver wins, switch the server
server = (server == 'A') ? 'B' : 'A';
}
}
// Output the final scores
printf("Alice's score: %d\n", alice_score);
printf("Bob's score: %d\n", bob_score);

return 0;
}

ALGORITHM

1. Initialize alice_score and bob_score to 0.


2. Set server to 'A' (Alice starts as the server).
3. For each point:
• If the server wins the point (based on the string of 'A' or 'B'), update
the server's score.
• If the receiver wins, switch the server.
4. After processing all points, print the scores for both players.

OUTPUT
PROGRAM 11

Your best friend has a very interesting necklace with n pearls. On each of the
pearls of the necklace there is an integer. However, your friend wants to
modify the necklace a bit and asks you for help. She wants to move the first
pearl k spots to the left (and do so with all other pearls). For example: if the
necklace was originally 1,5,3,4,21,5,3,4,2 and =2k=2, now it becomes
3,4,2,1,53,4,2,1,5. Help your best friend determine how the necklace will look
after the modification.

#include <stdio.h>

void rotateLeft(int arr[], int n, int k) {


k = k % n; // Effective rotation
printf("Rotated Necklace: ");
for (int i = k; i < n; i++) {
printf("%d ", arr[i]);
}
for (int i = 0; i < k; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {1, 5, 3, 4, 21, 5, 3, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
rotateLeft(arr, n, k);
return 0;
}

ALGORITHM

1. Calculate the effective rotation index: k=k%n.


2. Divide the array into two parts:
• Part 1: Elements from index 0 to k−1.
• Part 2: Elements from index k to n−1.
3. Concatenate Part 2 and Part 1 to form the rotated array.
4. Output the rotated array.
OUTPUT
PROGRAM 12

You have an array A of integers of size N, an array B ( initially empty ) and a


stack S ( initially empty ). You are allowed to do the following operations :
• Take the first element of array A and push it into S and remove it from
A.
• Take the top element from stack S, append it to the end of array B and
remove it from S.
You have to tell if it possible to move all the elements of array A to array B
using the above operations such that finally the array B is sorted in ascending
order.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Function to check if it's possible to sort array B


bool canSortArray(int A[], int N) {
int B[N]; // Array B
int B_index = 0; // Index for array B
int stack[N]; // Simulated stack
int top = -1; // Stack pointer

int expected = 1; // Expected element in sorted order

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


// Push the first element of A onto the stack
stack[++top] = A[i];

// Check if we can pop from the stack to B in sorted order


while (top != -1 && stack[top] == expected) {
B[B_index++] = stack[top--]; // Append to B and pop from stack
expected++;
}
}

// If all elements are moved and B is sorted, return true


return (B_index == N);
}

int main() {
int N;

// Input the size of the array


printf("Enter the size of array A: ");
scanf("%d", &N);

int A[N];

// Input elements of array A


printf("Enter %d elements of array A: ", N);
for (int i = 0; i < N; i++) {
scanf("%d", &A[i]);
}

// Check if it's possible to sort the array B


if (canSortArray(A, N)) {
printf("Yes, it is possible to sort array B in ascending order.\n");
} else {
printf("No, it is not possible to sort array B in ascending order.\n");
}

return 0;
}

ALGORITHM

1. Initialize an empty stack S and an empty array B.


2. For each element in array A:
• Push the current element from A into S.
• Check if the top of S matches the expected smallest value.
3. If the top of S matches the expected value:
• Pop the element from S and append it to B.
• Increment the expected value.
4. 4Repeat the process until all elements are moved to B.
5. 5If B contains all elements of A in ascending order, output "Yes";
otherwise, output "No".
OUTPUT

PROGRAM 13

Design and implement a food ordering system for a restaurant using a circular
queue data structure. The system should manage incoming food orders from
multiple customers and allocate kitchen staff to prepare the orders efficiently.

The system should allow the user to perform the following operations:

1. Enqueue a food order into the queue with a unique order number,
customer name, and list of food items ordered.
2. Dequeue an order from the queue (when it has been processed by the
kitchen staff).
3. Display the current state of the queue with the order numbers, customer
names, and list of food items ordered.
4. Exit the program.

#include <stdio.h>
#include <string.h>
#define MAX 5
typedef struct {
int orderNumber;
char customerName[30];
char foodItems[100];
} Order;

Order queue[MAX];
int front = -1, rear = -1;

void enqueue(Order order) {


if ((rear + 1) % MAX == front) {
printf("Queue is full! Cannot add more orders.\n");
return;
}
if (front == -1) front = 0;
rear = (rear + 1) % MAX;
queue[rear] = order;
printf("Order added successfully.\n");
}

void dequeue() {
if (front == -1) {
printf("Queue is empty! No orders to process.\n");
return;
}
printf("Processing Order #%d\n", queue[front].orderNumber);
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
}

void displayQueue() {
if (front == -1) {
printf("Queue is empty!\n");
return;
}
printf("Current Orders in Queue:\n");
int i = front;
while (1) {
printf("Order #%d, Customer: %s, Items: %s\n", queue[i].orderNumber,
queue[i].customerName, queue[i].foodItems);
if (i == rear) break;
i = (i + 1) % MAX;
}
}

int main() {
int choice;

Order order;
while (1) {
printf("\n1. Add Order\n2. Process Order\n3. View Orders\n4.
Exit\nChoose: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter Order Number: ");
scanf("%d", &order.orderNumber);
printf("Enter Customer Name: ");
scanf("%s", order.customerName);
printf("Enter Food Items: ");
scanf("%s", order.foodItems);
enqueue(order);
} else if (choice == 2) {
dequeue();
} else if (choice == 3) {
displayQueue();
} else {
break;
}
}
return 0;
}
ALGORITHM

1. Initialize Circular Queue:


• Set front and rear pointers to -1.
• Define the maximum size of the queue.
2. Enqueue Operation:
• Check if the queue is full: (rear+1) % maxSize == front.
• If not full, insert the order at (rear+1) % maxSize and update the rear
pointer.
• If the queue was empty, set front to 0.
3. Dequeue Operation:
• Check if the queue is empty: front==−1.
• If not empty, remove the order at the front and update the front
pointer to (front+1) % maxSize.
• If front equals rear, reset both to -1 (queue becomes empty).
4. Display Queue:
• Iterate from front to rear, wrapping around using modulo.
5. Allow the user to perform enqueue, dequeue, and display operations in a
loop until they choose to exit.
OUTPUT
PROGRAM 14

Alice and Bob are playing a game with a binary string S of length N and an
empty string T. They both take turns and Alice plays first. 
• In Alice's turn, she picks the first character of string S, appends the
character to either the front or back of string T and deletes the chosen
character from string S. 
• In Bob's turn, he picks the last character of string S, appends the
character to either the front or back of string T and deletes the chosen
character from string �S.
The game stops when S becomes empty. Alice wants the resultant string T to
be lexicographically smallest, while Bob wants the resultant string T to be
lexicographically largest possible. Find the resultant string T, if both of them
play optimally

#include <stdio.h>
#include <string.h>

// Function to append a character to the front of a string


void appendToFront(char *str, char c) {
int len = strlen(str);
for (int i = len; i >= 0; i--) {
str[i + 1] = str[i];
}
str[0] = c;
}

// Function to append a character to the back of a string


void appendToBack(char *str, char c) {
int len = strlen(str);
str[len] = c;
str[len + 1] = '\0';
}

int main() {
char S[101], T[101] = ""; // S for input string, T for result
int N;

// Input the binary string S


printf("Enter the binary string S: ");
scanf("%s", S);

N = strlen(S);
int left = 0, right = N - 1; // Pointers for the start and end of S
int turn = 0; // 0 for Alice, 1 for Bob

while (left <= right) {


if (turn == 0) {
// Alice's turn: Choose the lexicographically smallest character
if (S[left] <= S[right]) {
appendToFront(T, S[left++]);
} else {
appendToFront(T, S[right--]);
}
} else {
// Bob's turn: Choose the lexicographically largest character
if (S[left] >= S[right]) {
appendToBack(T, S[left++]);
} else {
appendToBack(T, S[right--]);
}
}
turn = 1 - turn; // Switch turns
}

// Output the resultant string T


printf("The resultant string T is: %s\n", T);

return 0;
}

ALGORITHM

1. Start with an empty string T and two pointers:


• start: pointing to the first character of S.
• end: pointing to the last character of S.
2. Alternate turns between Alice and Bob:
• Alice picks the lexicographically smaller of the two characters at start
and end, appending it to T.
• Bob picks the lexicographically larger of the two characters at start
and end, appending it to T.
3. Update start or end depending on the character chosen.
4. Repeat until S becomes empty.
5. Output the resultant string T.
OUTPUT

PROGRAM 15

//C program to reverse a singly linked list

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node


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

// Function to create a new node


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

// Function to reverse the linked list


struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;

while (current != NULL) {


next = current->next; // Save the next node
current->next = prev; // Reverse the link
prev = current; // Move prev to current
current = next; // Move current to next
}

return prev; // New head of the reversed list


}

// Function to display the linked list


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

int main() {
struct Node* head = NULL;
struct Node* temp = NULL;
int n, value;

// Input the number of nodes


printf("Enter the number of nodes: ");
scanf("%d", &n);

// Create the linked list


printf("Enter the values for the nodes:\n");
for (int i = 0; i < n; i++) {
printf("Node %d: ", i + 1);
scanf("%d", &value);
struct Node* newNode = createNode(value);
if (head == NULL) {
head = newNode;
} else {
temp->next = newNode;
}
temp = newNode;
}

// Display the original list


printf("\nOriginal Linked List:\n");
displayList(head);

// Reverse the list


head = reverseList(head);
// Display the reversed list

printf("\nReversed Linked List:\n");


displayList(head);

return 0;
}

ALGORITHM

1. Initialize three pointers:


• prev: initially set to NULL.
• current: initially set to the head of the list.
• next: to temporarily store the next node.
2. Traverse the linked list:
• Save the next node in next: next=current→next.
• Reverse the current node's pointer: current→next=prev.
• Move prev to current and current to next.
3. When current becomes NULL, prev will point to the new head of the
reversed list.
4. Return prev as the new head.

OUTPUT

You might also like