0% found this document useful (0 votes)
18 views85 pages

FY-Lab Exam

Uploaded by

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

FY-Lab Exam

Uploaded by

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

FY-Lab Exam AY-2023-24 SEM-1

question 1

#include <stdio.h>

int main() {

// Declare variables

char str[100];

int alphabets = 0, digits = 0;

// Input string from user

printf("Enter a string: ");

scanf("%s", str);

// Iterate through each character in the string

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

// Check if the character is an alphabet

if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {

alphabets++;

// Check if the character is a digit

else if (str[i] >= '0' && str[i] <= '9') {

digits++;

// Display the result

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

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

return 0;
}

question 2

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

// Structure to represent a stack

struct Stack {

char *arr;

int top;

};

// Function to initialize a stack

struct Stack* initializeStack(int size) {

struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));

stack->arr = (char*)malloc(size * sizeof(char));

stack->top = -1;

return stack;

// Function to check if the stack is empty

bool isEmpty(struct Stack* stack) {

return stack->top == -1;

// Function to push an element onto the stack

void push(struct Stack* stack, char element) {

stack->arr[++stack->top] = element;

}
// Function to pop an element from the stack

char pop(struct Stack* stack) {

if (!isEmpty(stack)) {

return stack->arr[stack->top--];

return '\0'; // Return null character if the stack is empty

// Function to check if the given string of brackets is valid

bool isValid(char* s) {

int length = 0;

while (s[length] != '\0') {

length++;

// Initialize a stack

struct Stack* stack = initializeStack(length);

// Traverse the string

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

// If the current character is an opening bracket, push it onto the stack

if (s[i] == '(' || s[i] == '[' || s[i] == '{') {

push(stack, s[i]);

// If the current character is a closing bracket

else if (s[i] == ')' || s[i] == ']' || s[i] == '}') {

// Pop the top element from the stack

char topElement = pop(stack);

// Check if the popped bracket matches the current closing bracket


if ((s[i] == ')' && topElement != '(') ||

(s[i] == ']' && topElement != '[') ||

(s[i] == '}' && topElement != '{')) {

free(stack->arr);

free(stack);

return false;

// Check if the stack is empty

bool result = isEmpty(stack);

// Free the memory allocated for the stack

free(stack->arr);

free(stack);

return result;

int main() {

// Test cases

char input1[] = "()";

char input2[] = "([]{})";

char input3[] = "([{";

// Check and display the results

printf("Test Case 1: %s\n", isValid(input1) ? "Valid" : "Invalid");

printf("Test Case 2: %s\n", isValid(input2) ? "Valid" : "Invalid");

printf("Test Case 3: %s\n", isValid(input3) ? "Valid" : "Invalid");


return 0;

q3

#include <stdio.h>

#include <string.h>

// Function to find the length of a string

int findLength(char s[]) {

int length = 0;

while (s[length] != '\0') {

length++;

return length;

// Function to print the string in reverse order

void printReverse(char s[]) {

int length = findLength(s);

for (int i = length - 1; i >= 0; i--) {

printf("%c", s[i]);

printf("\n");

// Function to copy string s into s1 and print it

void copyAndPrint(char s[], char s1[]) {

strcpy(s1, s);

printf("Copied String (s1): %s\n", s1);

}
// Function to concatenate s and s2 and print the result

void concatenateAndPrint(char s[], char s2[]) {

strcat(s, s2);

printf("Concatenated String: %s\n", s);

int main() {

char s[100], s1[100], s2[100];

// Accepting input string

printf("Enter a string: ");

scanf("%s", s);

// Finding length of the string and printing it

int length = findLength(s);

printf("Length of the string: %d\n", length);

// Printing the string in reverse order

printf("String in reverse order: ");

printReverse(s);

// Copying string s into s1 and printing it

copyAndPrint(s, s1);

// Accepting another string s2

printf("Enter another string (s2): ");

scanf("%s", s2);

// Concatenating s and s2 and printing the result

concatenateAndPrint(s, s2);
return 0;

q4

#include <stdio.h>

#include <string.h>

// Function to find the length of a string using pointers

int findLength(char *s) {

int length = 0;

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

length++;

s++;

return length;

// Function to print the string in reverse order using pointers

void printReverse(char *s) {

int length = findLength(s);

for (int i = length - 1; i >= 0; i--) {

printf("%c", *(s + i));

printf("\n");

// Function to copy string s into s1 using pointers and print it

void copyAndPrint(char *s, char *s1) {

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


*s1 = *s;

s++;

s1++;

*s1 = '\0'; // Null-terminate the destination string

printf("Copied String (s1): %s\n", s1);

int main() {

char s[100], s1[100];

// Accepting input string

printf("Enter a string: ");

scanf("%s", s);

// Finding length of the string using pointers and printing it

int length = findLength(s);

printf("Length of the string: %d\n", length);

// Printing the string in reverse order using pointers

printf("String in reverse order: ");

printReverse(s);

// Copying string s into s1 using pointers and printing it

copyAndPrint(s, s1);

return 0;

q5
#include <stdio.h>

#include <string.h>

#include <stdbool.h>

// Function to check if a string is a palindrome

bool isPalindrome(char *s) {

int length = strlen(s);

for (int i = 0; i < length / 2; i++) {

if (s[i] != s[length - i - 1]) {

return false;

return true;

int main() {

char input[100];

// Test Case 1

printf("Test Case 1:\n");

printf("Input: MADAM\n");

bool result1 = isPalindrome("MADAM");

printf("Output: %s\n", result1 ? "true" : "false");

printf("\n");

// Test Case 2

printf("Test Case 2:\n");

printf("Input: CAR\n");

bool result2 = isPalindrome("CAR");

printf("Output: %s\n", result2 ? "true" : "false");


return 0;

q6

#include <stdio.h>

// Function to find the minimum number in an array

int findMin(int arr[], int size) {

int min = arr[0];

for (int i = 1; i < size; i++) {

if (arr[i] < min) {

min = arr[i];

return min;

// Function to find the maximum number in an array

int findMax(int arr[], int size) {

int max = arr[0];

for (int i = 1; i < size; i++) {

if (arr[i] > max) {

max = arr[i];

return max;

// Function to search for a particular number in an array

int searchNumber(int arr[], int size, int target) {


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

if (arr[i] == target) {

return i; // Return the index if found

return -1; // Return -1 if not found

int main() {

int limit;

// Accepting the limit of the array

printf("Enter the limit of the array: ");

scanf("%d", &limit);

// Declaring the array with the given limit

int arr[limit];

// Reading integer elements into the array

printf("Enter %d integer elements into the array:\n", limit);

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

scanf("%d", &arr[i]);

// Printing the minimum and maximum numbers from the array

printf("Minimum number in the array: %d\n", findMin(arr, limit));

printf("Maximum number in the array: %d\n", findMax(arr, limit));

// Searching for a particular number in the array

int target;

printf("Enter the number to search in the array: ");


scanf("%d", &target);

int result = searchNumber(arr, limit, target);

if (result != -1) {

printf("Number %d found at index %d in the array.\n", target, result);

} else {

printf("Number %d not found in the array.\n", target);

return 0;

q7

#include <stdio.h>

#include <string.h>

// Function to shuffle the string based on the given indices

void shuffleString(char *s, int *indices, int size) {

char result[size + 1]; // +1 for the null terminator

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

result[indices[i]] = s[i];

result[size] = '\0'; // Null-terminate the result string

// Copy the shuffled string back to the original string

strcpy(s, result);

int main() {
// Test Case 1

char s1[] = "codeleet";

int indices1[] = {4, 5, 6, 7, 0, 2, 1, 3};

printf("Test Case 1:\n");

printf("Input: s = \"%s\", indices = [4, 5, 6, 7, 0, 2, 1, 3]\n", s1);

// Shuffling the string based on the indices

shuffleString(s1, indices1, sizeof(indices1) / sizeof(indices1[0]));

printf("Output: \"%s\"\n", s1);

printf("\n");

// Test Case 2

char s2[] = "abc";

int indices2[] = {0, 1, 2};

printf("Test Case 2:\n");

printf("Input: s = \"%s\", indices = [0, 1, 2]\n", s2);

// Shuffling the string based on the indices

shuffleString(s2, indices2, sizeof(indices2) / sizeof(indices2[0]));

printf("Output: \"%s\"\n", s2);

return 0;

q8

#include <stdio.h>
int main() {

int n = 5; // You can change this value to adjust the pattern size

// Print the pattern in ascending order

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

for (char ch = 'A'; ch < 'A' + i; ch++) {

printf("%c ", ch);

printf("\n");

// Print the pattern in descending order

for (int i = n - 1; i >= 1; i--) {

for (char ch = 'A'; ch < 'A' + i; ch++) {

printf("%c ", ch);

printf("\n");

return 0;

#include <stdio.h>

// Function to calculate the factorial of a number

long long factorial(int num) {

if (num == 0 || num == 1) {

return 1;

} else {
return num * factorial(num - 1);

int main() {

// Print factorial of numbers from 1 to 10

for (int i = 1; i <= 10; i++) {

printf("Factorial of %d: %lld\n", i, factorial(i));

return 0;

q9

#include <stdio.h>

int main() {

int n = 5; // You can change this value to adjust the pattern size

// Print the first pattern

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

for (int j = 1; j <= i; j++) {

printf("%d ", j);

printf("\n");

printf("\n");

// Print the second pattern


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

for (int j = 1; j <= i; j++) {

printf("%c ", 'E' - j + 1);

printf("\n");

return 0;

#include <stdio.h>

#include <stdbool.h>

// Function to check if a number is prime

bool isPrime(int num) {

if (num <= 1) {

return false;

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) {

return false;

return true;

int main() {

int start, end;


// Accepting input from the user

printf("Enter the starting number: ");

scanf("%d", &start);

printf("Enter the ending number: ");

scanf("%d", &end);

// Print prime numbers between start and end

printf("Prime numbers between %d and %d are: \n", start, end);

for (int i = start; i <= end; i++) {

if (isPrime(i)) {

printf("%d\n", i);

return 0;

q10

#include <stdio.h>

#include <string.h>

#include <ctype.h>

#define MAX_CHARACTERS 256

// Function to calculate and print the frequency of each character in a string

void printCharacterFrequency(char *str) {

int frequency[MAX_CHARACTERS] = {0};


// Count the frequency of each character in the string

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

if (isalpha(str[i])) {

frequency[tolower(str[i])]++;

// Print the frequency of each character

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

if (frequency[i] > 0) {

printf("Frequency of %c: %d\n", i, frequency[i]);

int main() {

char inputString[1000];

// Accepting input string from the user

printf("Enter a string: ");

fgets(inputString, sizeof(inputString), stdin);

// Print the frequency of each character in the string

printCharacterFrequency(inputString);

return 0;

q11

#include <stdio.h>
// Function to print Fibonacci series up to n terms

void printFibonacci(int n) {

int first = 0, second = 1, next;

printf("Fibonacci series up to %d terms:\n", n);

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

printf("%d", first);

if (i < n - 1) {

printf(", ");

next = first + second;

first = second;

second = next;

printf("\n");

int main() {

int terms;

// Accepting input from the user

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

scanf("%d", &terms);

// Print Fibonacci series up to the specified number of terms

printFibonacci(terms);
return 0;

q12

#include <stdio.h>

#include <ctype.h>

// Function to count the number of vowels and consonants in a string

void countVowelsAndConsonants(char *str, int *vowels, int *consonants) {

*vowels = *consonants = 0;

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

char ch = tolower(str[i]);

if (ch >= 'a' && ch <= 'z') {

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

(*vowels)++;

} else {

(*consonants)++;

int main() {

char inputString[1000];

int vowels, consonants;

// Accepting input string from the user

printf("Enter a string: ");


fgets(inputString, sizeof(inputString), stdin);

// Count the number of vowels and consonants

countVowelsAndConsonants(inputString, &vowels, &consonants);

// Print the results

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

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

return 0;

q13

#include <stdio.h>

// Function to convert decimal to binary

void decimalToBinary(int decimal) {

int binary[32];

int i = 0;

// Handling the case when the input is 0

if (decimal == 0) {

printf("Binary: 0\n");

return;

// Converting decimal to binary

while (decimal > 0) {

binary[i] = decimal % 2;

decimal = decimal / 2;

i++;
}

// Printing the binary representation

printf("Binary: ");

for (int j = i - 1; j >= 0; j--) {

printf("%d", binary[j]);

printf("\n");

int main() {

int decimal;

// Accepting input from the user

printf("Enter a decimal number: ");

scanf("%d", &decimal);

// Convert decimal to binary and print the result

decimalToBinary(decimal);

return 0;

q14

#include <stdio.h>

// Function to reverse an array using pointers

void reverseArray(int *arr, int size) {

int *start = arr;

int *end = arr + size - 1;


while (start < end) {

// Swap the values pointed by start and end

int temp = *start;

*start = *end;

*end = temp;

// Move the pointers towards each other

start++;

end--;

// Function to print an array

void printArray(int *arr, int size) {

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

printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {1, 2, 3, 4, 5};

int size = sizeof(arr) / sizeof(arr[0]);

// Printing the original array

printf("Original Array: ");

printArray(arr, size);

// Reversing the array using pointers

reverseArray(arr, size);
// Printing the reversed array

printf("Reversed Array: ");

printArray(arr, size);

return 0;

q15

#include <stdio.h>

// Function to check if a number is a perfect number

int isPerfect(int num) {

int sum = 1; // Start with 1 because every number is divisible by 1

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) {

sum += i;

if (i * i != num) {

sum += num / i;

return sum == num;

// Function to print all perfect numbers in a given interval

void printPerfectNumbers(int lower, int upper) {

printf("All perfect numbers between %d and %d are: ", lower, upper);


for (int i = lower; i <= upper; i++) {

if (isPerfect(i)) {

printf("%d ", i);

printf("\n");

int main() {

int lower, upper;

// Accepting input from the user

printf("Enter lower limit to print perfect numbers: ");

scanf("%d", &lower);

printf("Enter upper limit to print perfect numbers: ");

scanf("%d", &upper);

// Print all perfect numbers in the given interval

printPerfectNumbers(lower, upper);

return 0;

q16

#include <stdio.h>

#include <string.h>

// Structure to represent student details

struct Student {
char name[50];

char mobileNumber[15];

float marks[5];

float totalMarks;

};

// Function to read details of n students

void readStudentDetails(struct Student students[], int n) {

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

printf("Enter details for student %d:\n", i + 1);

printf("Name: ");

scanf("%s", students[i].name);

printf("Mobile Number: ");

scanf("%s", students[i].mobileNumber);

printf("Enter marks for 5 subjects:\n");

for (int j = 0; j < 5; j++) {

printf("Subject %d: ", j + 1);

scanf("%f", &students[i].marks[j]);

// Calculate total marks for each student

students[i].totalMarks = 0;

for (int j = 0; j < 5; j++) {

students[i].totalMarks += students[i].marks[j];

printf("\n");

}
}

// Function to print details of n students

void printStudentDetails(struct Student students[], int n) {

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

printf("Details for student %d:\n", i + 1);

printf("Name: %s\n", students[i].name);

printf("Mobile Number: %s\n", students[i].mobileNumber);

printf("Total Marks: %.2f\n", students[i].totalMarks);

printf("\n");

// Function to find and print details of top 5 students based on total marks

void printTopStudents(struct Student students[], int n) {

// Sorting the students based on total marks in descending order

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

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

if (students[j].totalMarks < students[j + 1].totalMarks) {

// Swap the students

struct Student temp = students[j];

students[j] = students[j + 1];

students[j + 1] = temp;

printf("Top 5 Students:\n");

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


printf("%d. Name: %s, Mobile Number: %s, Total Marks: %.2f\n", i + 1, students[i].name,
students[i].mobileNumber, students[i].totalMarks);

int main() {

int n;

// Accepting the number of students from the user

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

scanf("%d", &n);

// Declare an array of structures to store details of n students

struct Student students[n];

// Read details of n students

readStudentDetails(students, n);

// Print details of n students

printf("Details of all students:\n");

printStudentDetails(students, n);

// Print details of top 5 students based on total marks

printTopStudents(students, n);

return 0;

q18

#include <stdio.h>
// Structure to represent student details

struct Student {

int rollNo;

char name[50];

float marks[5];

float totalMarks;

char grade;

};

// Function to calculate the total marks and grade for a student

void calculateGrade(struct Student *student) {

student->totalMarks = 0;

// Calculate total marks for each student

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

student->totalMarks += student->marks[i];

// Assign the grade based on the total marks

if (student->totalMarks >= 76 && student->totalMarks <= 99) {

student->grade = 'D'; // Distinction

} else if (student->totalMarks >= 60 && student->totalMarks <= 75) {

student->grade = 'F'; // First Class

} else if (student->totalMarks >= 50 && student->totalMarks <= 59) {

student->grade = 'S'; // Second Class

} else if (student->totalMarks >= 40 && student->totalMarks <= 49) {

student->grade = 'P'; // Pass Class

} else {

student->grade = 'F'; // Fail

}
}

// Function to print details of a student

void printStudentDetails(struct Student *student) {

printf("Roll No: %d\n", student->rollNo);

printf("Name: %s\n", student->name);

printf("Total Marks: %.2f\n", student->totalMarks);

printf("Grade: %c\n", student->grade);

printf("\n");

int main() {

int n;

// Accepting the number of students from the user

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

scanf("%d", &n);

// Declare an array of structures to store details of n students

struct Student students[n];

// Read details of n students

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

printf("Enter details for student %d:\n", i + 1);

printf("Roll No: ");

scanf("%d", &students[i].rollNo);

printf("Name: ");

scanf("%s", students[i].name);
printf("Enter marks for 5 subjects:\n");

for (int j = 0; j < 5; j++) {

printf("Subject %d: ", j + 1);

scanf("%f", &students[i].marks[j]);

// Calculate total marks and grade for each student

calculateGrade(&students[i]);

// Print details of all students

printf("Details of all students:\n");

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

printf("Details for student %d:\n", i + 1);

printStudentDetails(&students[i]);

return 0;

q19

#include <stdio.h>

// Function to swap the contents of two arrays

void swapArrays(int arr1[], int arr2[], int size) {

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

// Swap elements at each index

int temp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = temp;
}

// Function to print the elements of an array

void printArray(int arr[], int size) {

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

printf("%d ", arr[i]);

printf("\n");

int main() {

int size;

// Accepting the size of the arrays from the user

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

scanf("%d", &size);

// Declare two arrays of size 'size'

int array1[size], array2[size];

// Accepting elements for the first array

printf("Enter elements for the first array:\n");

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

printf("Element %d: ", i + 1);

scanf("%d", &array1[i]);

// Accepting elements for the second array

printf("Enter elements for the second array:\n");

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


printf("Element %d: ", i + 1);

scanf("%d", &array2[i]);

// Print the original arrays

printf("Original Arrays:\n");

printf("Array 1: ");

printArray(array1, size);

printf("Array 2: ");

printArray(array2, size);

// Swap the arrays using the function

swapArrays(array1, array2, size);

// Print the swapped arrays

printf("Arrays after swapping:\n");

printf("Array 1: ");

printArray(array1, size);

printf("Array 2: ");

printArray(array2, size);

return 0;

q20

#include <stdio.h>

// Function to count the number of digits and calculate the sum of digits

void countAndSumDigits(int number, int *count, int *sum) {

*count = 0;
*sum = 0;

// Handling the case when the input is negative

if (number < 0) {

number = -number;

// Counting the number of digits and calculating the sum

while (number != 0) {

*sum += number % 10;

number /= 10;

(*count)++;

int main() {

int num, digitCount, digitSum;

// Accepting input from the user

printf("Enter an integer: ");

scanf("%d", &num);

// Count the number of digits and calculate the sum

countAndSumDigits(num, &digitCount, &digitSum);

// Print the results

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

printf("Sum of digits: %d\n", digitSum);

return 0;

}
q21

#include <stdio.h>

#include <stdlib.h>

// Function to read elements of an array

void readArray(int *arr, int size) {

printf("Enter elements of the array:\n");

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

printf("Element %d: ", i + 1);

scanf("%d", &arr[i]);

// Function to print elements of an array

void printArray(int *arr, int size) {

printf("Array: ");

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

printf("%d ", arr[i]);

printf("\n");

// Function to calculate the sum of two arrays

void sumArrays(int *arr1, int *arr2, int *result, int size) {

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

result[i] = arr1[i] + arr2[i];

}
int main() {

int size;

// Accepting the size of the arrays from the user

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

scanf("%d", &size);

// Dynamically allocate memory for the arrays

int *array1 = (int *)malloc(size * sizeof(int));

int *array2 = (int *)malloc(size * sizeof(int));

int *sumResult = (int *)malloc(size * sizeof(int));

if (array1 == NULL || array2 == NULL || sumResult == NULL) {

printf("Memory allocation failed. Exiting...\n");

return 1;

// Read elements for the first array

printf("\nEnter elements for the first array:\n");

readArray(array1, size);

// Read elements for the second array

printf("\nEnter elements for the second array:\n");

readArray(array2, size);

// Calculate the sum of arrays using the function

sumArrays(array1, array2, sumResult, size);

// Print the original arrays and the result

printf("\nOriginal Arrays:\n");

printArray(array1, size);
printArray(array2, size);

printf("\nSum of Arrays:\n");

printArray(sumResult, size);

// Free dynamically allocated memory

free(array1);

free(array2);

free(sumResult);

return 0;

q22

#include <stdio.h>

// Function to accept matrix elements

void acceptMatrix(int matrix[][100], int rows, int columns) {

printf("Enter elements of the matrix:\n");

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

for (int j = 0; j < columns; j++) {

printf("Element [%d][%d]: ", i + 1, j + 1);

scanf("%d", &matrix[i][j]);

// Function to print matrix elements

void printMatrix(int matrix[][100], int rows, int columns) {

printf("Matrix:\n");
for (int i = 0; i < rows; i++) {

for (int j = 0; j < columns; j++) {

printf("%d ", matrix[i][j]);

printf("\n");

// Function to print transpose of a matrix

void printTranspose(int matrix[][100], int rows, int columns) {

printf("Transpose of the matrix:\n");

for (int j = 0; j < columns; j++) {

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

printf("%d ", matrix[i][j]);

printf("\n");

// Function to print diagonal elements of a matrix

void printDiagonal(int matrix[][100], int rows, int columns) {

printf("Diagonal elements of the matrix:\n");

for (int i = 0; i < rows && i < columns; i++) {

printf("%d ", matrix[i][i]);

printf("\n");

int main() {

int rows, columns;


// Accepting the number of rows and columns for the matrices

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

scanf("%d", &rows);

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

scanf("%d", &columns);

// Declare two matrices

int matrix1[100][100], matrix2[100][100];

// Accept elements for the first matrix

printf("\nFor Matrix 1:\n");

acceptMatrix(matrix1, rows, columns);

// Accept elements for the second matrix

printf("\nFor Matrix 2:\n");

acceptMatrix(matrix2, rows, columns);

// Print the original matrices

printf("\nOriginal Matrices:\n");

printMatrix(matrix1, rows, columns);

printMatrix(matrix2, rows, columns);

// Print the transpose of matrices

printf("\nTranspose of Matrices:\n");

printTranspose(matrix1, rows, columns);

printTranspose(matrix2, rows, columns);

// Print diagonal elements of matrices

printf("\nDiagonal elements of Matrices:\n");

printDiagonal(matrix1, rows, columns);


printDiagonal(matrix2, rows, columns);

return 0;

q23

#include <stdio.h>

// Structure to represent a date

struct Date {

int day;

int month;

int year;

};

// Function to check if a year is a leap year

int isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

// Function to add days to a date

void addDays(struct Date *date, int days) {

while (days > 0) {

int daysInMonth;

switch (date->month) {

case 1: case 3: case 5: case 7: case 8: case 10: case 12:

daysInMonth = 31;

break;

case 4: case 6: case 9: case 11:


daysInMonth = 30;

break;

case 2:

daysInMonth = isLeapYear(date->year) ? 29 : 28;

break;

default:

printf("Invalid month\n");

return;

if (days > daysInMonth - date->day) {

days -= daysInMonth - date->day + 1;

date->day = 1;

if (date->month == 12) {

date->month = 1;

date->year++;

} else {

date->month++;

} else {

date->day += days;

days = 0;

int main() {

struct Date currentDate;

// Accepting input for the current date


printf("Enter the current date (dd mm yy): ");

scanf("%d %d %d", &currentDate.day, &currentDate.month, &currentDate.year);

// Adding 45 days to the current date

addDays(&currentDate, 45);

// Displaying the final date

printf("Final date: %02d/%02d/%02d\n", currentDate.day, currentDate.month, currentDate.year);

return 0;

q24

#include <stdio.h>

// Structure to store student information

struct Student {

int rollNo;

char name[50];

int age;

char address[100];

};

// Function to print the names of students with age 14

void printNamesWithAge14(struct Student students[], int size) {

printf("Names of students with age 14:\n");

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

if (students[i].age == 14) {

printf("%s\n", students[i].name);

}
}

printf("\n");

// Function to print the names of students with even roll numbers

void printNamesWithEvenRollNo(struct Student students[], int size) {

printf("Names of students with even roll numbers:\n");

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

if (students[i].rollNo % 2 == 0) {

printf("%s\n", students[i].name);

printf("\n");

// Function to display details of a student based on roll number

void displayStudentDetails(struct Student students[], int size, int rollNo) {

int found = 0;

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

if (students[i].rollNo == rollNo) {

printf("Details of the student with roll number %d:\n", rollNo);

printf("Name: %s\n", students[i].name);

printf("Age: %d\n", students[i].age);

printf("Address: %s\n", students[i].address);

found = 1;

break;

if (!found) {

printf("Student with roll number %d not found.\n", rollNo);


}

printf("\n");

int main() {

// Declare an array of structures to store student information

struct Student students[5];

// Accept information for 5 students

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

printf("Enter details for student %d:\n", i + 1);

printf("Roll No: ");

scanf("%d", &students[i].rollNo);

printf("Name: ");

scanf("%s", students[i].name);

printf("Age (between 11 to 14): ");

scanf("%d", &students[i].age);

printf("Address: ");

scanf("%s", students[i].address);

printf("\n");

// Call functions to perform tasks

printNamesWithAge14(students, 5);

printNamesWithEvenRollNo(students, 5);
int searchRollNo;

printf("Enter the roll number to search: ");

scanf("%d", &searchRollNo);

displayStudentDetails(students, 5, searchRollNo);

return 0;

q25

#include <stdio.h>

// Structure to store employee information

struct Employee {

char name[50];

float salary;

int hoursOfWorkPerDay;

};

// Function to increase salary based on hours of work per day

void increaseSalary(struct Employee *employee) {

if (employee->hoursOfWorkPerDay >= 12) {

employee->salary += 12000;

} else if (employee->hoursOfWorkPerDay >= 10) {

employee->salary += 8000;

} else if (employee->hoursOfWorkPerDay >= 8) {

employee->salary += 4000;

int main() {
// Declare an array of structures to store employee information

struct Employee employees[10];

// Accept information for 10 employees

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

printf("Enter details for employee %d:\n", i + 1);

printf("Name: ");

scanf("%s", employees[i].name);

printf("Salary: ");

scanf("%f", &employees[i].salary);

printf("Hours of work per day: ");

scanf("%d", &employees[i].hoursOfWorkPerDay);

printf("\n");

// Increase salary based on hours of work per day

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

increaseSalary(&employees[i]);

// Print the names of all employees along with their final salaries

printf("Employee details after salary increase:\n");

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

printf("%s %.2f %d\n", employees[i].name, employees[i].salary,


employees[i].hoursOfWorkPerDay);

return 0;
}

q26

#include <stdio.h>

int main() {

FILE *file;

char fileName[100];

char line[100];

// Accepting the file name from the user

printf("Enter the file name: ");

scanf("%s", fileName);

// Opening the file in read mode

file = fopen(fileName, "r");

if (file == NULL) {

printf("Error opening file %s\n", fileName);

return 1;

// Reading the first line from the file

if (fgets(line, sizeof(line), file) != NULL) {

printf("First line from the file:\n%s", line);

} else {

printf("File is empty.\n");

// Closing the file


fclose(file);

return 0;

q27

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a student

struct Student {

int id;

char name[50];

float marks;

};

// Function to write records to the file

void writeRecords(FILE *file, struct Student students[], int numRecords) {

fwrite(students, sizeof(struct Student), numRecords, file);

// Function to read all records from the file

void readRecords(FILE *file, struct Student students[], int numRecords) {

fread(students, sizeof(struct Student), numRecords, file);

// Function to search for a particular student and print details

void searchStudent(FILE *file, int searchId) {

struct Student student;

fseek(file, 0, SEEK_SET); // Move the file pointer to the beginning


while (fread(&student, sizeof(struct Student), 1, file) == 1) {

if (student.id == searchId) {

printf("Student found!\n");

printf("ID: %d\nName: %s\nMarks: %.2f\n", student.id, student.name, student.marks);

return;

printf("Student with ID %d not found.\n", searchId);

int main() {

FILE *file;

struct Student students[5];

// Open the file in binary read-write mode

file = fopen("studentDatabase.dat", "wb+");

if (file == NULL) {

perror("Error opening file");

return 1;

// Write five records to the file

printf("Enter details for 5 students:\n");

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

printf("Student %d:\n", i + 1);

printf("ID: ");

scanf("%d", &students[i].id);

printf("Name: ");

scanf("%s", students[i].name);
printf("Marks: ");

scanf("%f", &students[i].marks);

writeRecords(file, students, 5);

// Read all records from the file

printf("\nReading all records from the file:\n");

readRecords(file, students, 5);

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

printf("ID: %d\nName: %s\nMarks: %.2f\n\n", students[i].id, students[i].name,


students[i].marks);

// Search for a particular student

int searchId;

printf("Enter the student ID to search: ");

scanf("%d", &searchId);

searchStudent(file, searchId);

// Close the file

fclose(file);

return 0;

q28

#include <stdio.h>

int main() {

FILE *sourceFile, *destinationFile;


char ch;

// Open source file in read mode

sourceFile = fopen("source.txt", "r");

if (sourceFile == NULL) {

perror("Error opening source file");

return 1;

// Open destination file in write mode

destinationFile = fopen("destination.txt", "w");

if (destinationFile == NULL) {

perror("Error opening destination file");

fclose(sourceFile);

return 1;

// Copy character by character from source to destination

while ((ch = fgetc(sourceFile)) != EOF) {

fputc(ch, destinationFile);

// Close both files

fclose(sourceFile);

fclose(destinationFile);

printf("File copy successful!\n");

return 0;

}
q29

#include <stdio.h>

// Function to accept matrix elements

void acceptMatrix(int rows, int cols, int matrix[rows][cols]) {

printf("Enter matrix elements:\n");

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

for (int j = 0; j < cols; j++) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &matrix[i][j]);

// Function to print a matrix

void printMatrix(int rows, int cols, int matrix[rows][cols]) {

printf("Matrix:\n");

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

for (int j = 0; j < cols; j++) {

printf("%d\t", matrix[i][j]);

printf("\n");

// Function to print the transpose of a matrix

void printTranspose(int rows, int cols, int matrix[rows][cols]) {

printf("Transpose of the matrix:\n");

for (int j = 0; j < cols; j++) {

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


printf("%d\t", matrix[i][j]);

printf("\n");

// Function to print the addition of two matrices

void printMatrixAddition(int rows, int cols, int matrix1[rows][cols], int matrix2[rows][cols]) {

printf("Addition of the matrices:\n");

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

for (int j = 0; j < cols; j++) {

printf("%d\t", matrix1[i][j] + matrix2[i][j]);

printf("\n");

int main() {

int rows, cols;

// Accept the number of rows and columns

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

scanf("%d", &rows);

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

scanf("%d", &cols);

int matrix1[rows][cols], matrix2[rows][cols];

// Accept elements for the first matrix

printf("\nFor Matrix 1:\n");

acceptMatrix(rows, cols, matrix1);


// Accept elements for the second matrix

printf("\nFor Matrix 2:\n");

acceptMatrix(rows, cols, matrix2);

// Print the matrices

printf("\n");

printMatrix(rows, cols, matrix1);

printf("\n");

printMatrix(rows, cols, matrix2);

printf("\n");

// Print the transpose of the matrices

printTranspose(rows, cols, matrix1);

printf("\n");

printTranspose(rows, cols, matrix2);

printf("\n");

// Print the addition of the matrices

printMatrixAddition(rows, cols, matrix1, matrix2);

return 0;

q30

#include <stdio.h>

// Function to accept matrix elements

void acceptMatrix(int rows, int cols, int matrix[rows][cols]) {

printf("Enter matrix elements:\n");


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

for (int j = 0; j < cols; j++) {

scanf("%d", &matrix[i][j]);

// Function to print matrix in row major format

void printRowMajor(int rows, int cols, int matrix[rows][cols]) {

printf("Row Major Format:\n");

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

for (int j = 0; j < cols; j++) {

printf("%d\t", matrix[i][j]);

printf("\n");

// Function to print matrix in column major format

void printColumnMajor(int rows, int cols, int matrix[rows][cols]) {

printf("Column Major Format:\n");

for (int j = 0; j < cols; j++) {

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

printf("%d\t", matrix[i][j]);

printf("\n");

int main() {

int rows, cols;


// Accept the number of rows and columns

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

scanf("%d", &rows);

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

scanf("%d", &cols);

int matrix[rows][cols];

// Accept elements for the matrix

printf("Enter matrix elements:\n");

acceptMatrix(rows, cols, matrix);

// Print the matrix in row major format

printf("\nRow Major Format:\n");

printRowMajor(rows, cols, matrix);

// Print the matrix in column major format

printf("\nColumn Major Format:\n");

printColumnMajor(rows, cols, matrix);

return 0;

q31

#include <stdio.h>

int main() {

FILE *file;
char fileName[50];

char ch;

int charCount = 0;

// Get the file name from the user

printf("Enter the file name: ");

scanf("%s", fileName);

// Open the file in read mode

file = fopen(fileName, "r");

if (file == NULL) {

perror("Error opening file");

return 1;

// Count characters and print each character on a new line

while ((ch = fgetc(file)) != EOF) {

charCount++;

printf("%c\n", ch);

// Print the total number of characters in the file

printf("Number of characters in the file: %d\n", charCount);

// Close the file

fclose(file);

return 0;

}
q32

#include <stdio.h>

#include <string.h>

// Function to delete all occurrences of a character from the string

void deleteCharacter(char *str, char ch) {

int i, j;

for (i = j = 0; str[i] != '\0'; i++) {

if (str[i] != ch) {

str[j++] = str[i];

str[j] = '\0'; // Null-terminate the modified string

int main() {

char inputString[100];

char characterToDelete;

// Get input string from the user

printf("Enter the string: ");

fgets(inputString, sizeof(inputString), stdin);

// Remove newline character if present

size_t len = strlen(inputString);

if (len > 0 && inputString[len - 1] == '\n') {

inputString[len - 1] = '\0';

}
// Get character to delete from the user

printf("Enter the character to delete: ");

scanf(" %c", &characterToDelete);

// Delete all occurrences of the character

deleteCharacter(inputString, characterToDelete);

// Print the modified string

printf("Output: %s\n", inputString);

return 0;

q33

#include <stdio.h>

#include <string.h>

// Function to insert a substring into a string at a specified position

void insertSubstring(char *mainStr, const char *subStr, int position) {

int mainLen = strlen(mainStr);

int subLen = strlen(subStr);

// Move characters to make space for the substring

for (int i = mainLen; i >= position; i--) {

mainStr[i + subLen] = mainStr[i];

// Insert the substring at the specified position


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

mainStr[position + i] = subStr[i];

int main() {

char firstString[100];

char secondString[50];

int position;

// Get input strings and position from the user

printf("Enter First String: ");

fgets(firstString, sizeof(firstString), stdin);

printf("Enter Second String: ");

fgets(secondString, sizeof(secondString), stdin);

printf("Enter the position to insert second string in first: ");

scanf("%d", &position);

// Remove newline characters if present

firstString[strcspn(firstString, "\n")] = '\0';

secondString[strcspn(secondString, "\n")] = '\0';

// Insert the second string into the first string

insertSubstring(firstString, secondString, position);

// Print the modified string

printf("Output: %s\n", firstString);

return 0;
}

q34

#include <stdio.h>

#include <ctype.h>

void convertToUpperCase(char *str) {

while (*str) {

*str = toupper(*str);

str++;

int main() {

char inputString[100];

// Get input string from the user

printf("Enter a string: ");

fgets(inputString, sizeof(inputString), stdin);

// Remove newline character if present

size_t len = strlen(inputString);

if (len > 0 && inputString[len - 1] == '\n') {

inputString[len - 1] = '\0';

// Convert the string to upper case

convertToUpperCase(inputString);
// Print the string in upper case

printf("String in upper case: %s\n", inputString);

return 0;

#include <stdio.h>

#include <string.h>

void reverseString(char *str) {

int length = strlen(str);

char *start = str;

char *end = str + length - 1;

while (start < end) {

// Swap characters using pointers

char temp = *start;

*start = *end;

*end = temp;

// Move pointers towards each other

start++;

end--;

int main() {

char inputString[100];

// Get input string from the user


printf("Enter a string: ");

fgets(inputString, sizeof(inputString), stdin);

// Remove newline character if present

size_t len = strlen(inputString);

if (len > 0 && inputString[len - 1] == '\n') {

inputString[len - 1] = '\0';

// Reverse the string using pointers

reverseString(inputString);

// Print the reversed string

printf("Reversed string: %s\n", inputString);

return 0;

q35

#include <stdio.h>

// Function to calculate a^b

long long power(int a, int b) {

long long result = 1;

while (b > 0) {

if (b % 2 == 1) {

result *= a;

}
a *= a;

b /= 2;

return result;

int main() {

int base, exponent;

// Get input values from the user

printf("Enter the base (a): ");

scanf("%d", &base);

printf("Enter the exponent (b): ");

scanf("%d", &exponent);

// Calculate and print the result

long long result = power(base, exponent);

printf("%d^%d = %lld\n", base, exponent, result);

return 0;

#include <stdio.h>

// Function to find the maximum number in an array

int findMax(int arr[], int size) {

int max = arr[0];


for (int i = 1; i < size; i++) {

if (arr[i] > max) {

max = arr[i];

return max;

int main() {

int size;

// Get the size of the array from the user

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

scanf("%d", &size);

int array[size];

// Get array elements from the user

printf("Enter the array elements:\n");

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

scanf("%d", &array[i]);

// Find and print the maximum number in the array

int max = findMax(array, size);

printf("Maximum number in the array: %d\n", max);

return 0;

}
q36

#include <stdio.h>

// Function to calculate HCF of two numbers

int calculateHCF(int a, int b) {

while (a != b) {

if (a > b) {

a -= b;

} else {

b -= a;

return a;

// Function to calculate LCM of two numbers

int calculateLCM(int a, int b) {

return (a * b) / calculateHCF(a, b);

int main() {

int num1, num2;

// Get input from the user

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

// Calculate and print HCF and LCM


int hcf = calculateHCF(num1, num2);

int lcm = calculateLCM(num1, num2);

printf("HCF of %d and %d is: %d\n", num1, num2, hcf);

printf("LCM of %d and %d is: %d\n", num1, num2, lcm);

return 0;

q37

#include <stdio.h>

// Function to accept matrix elements

void acceptMatrix(int rows, int cols, int matrix[rows][cols]) {

printf("Enter matrix elements:\n");

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

for (int j = 0; j < cols; j++) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &matrix[i][j]);

// Function to check if two matrices are equal

int areMatricesEqual(int rows1, int cols1, int matrix1[rows1][cols1],

int rows2, int cols2, int matrix2[rows2][cols2]) {

if (rows1 != rows2 || cols1 != cols2) {

return 0; // Matrices have different dimensions

}
for (int i = 0; i < rows1; i++) {

for (int j = 0; j < cols1; j++) {

if (matrix1[i][j] != matrix2[i][j]) {

return 0; // Matrices are not equal

return 1; // Matrices are equal

int main() {

int rows1, cols1, rows2, cols2;

// Accept the order of the first matrix from the user

printf("Enter the number of rows for Matrix 1: ");

scanf("%d", &rows1);

printf("Enter the number of columns for Matrix 1: ");

scanf("%d", &cols1);

// Accept the order of the second matrix from the user

printf("Enter the number of rows for Matrix 2: ");

scanf("%d", &rows2);

printf("Enter the number of columns for Matrix 2: ");

scanf("%d", &cols2);

// Check if the matrices can be compared for equality

if (rows1 != rows2 || cols1 != cols2) {

printf("Matrices are not equal because they have different dimensions.\n");

return 0;

}
int matrix1[rows1][cols1], matrix2[rows2][cols2];

// Accept elements for the first matrix

printf("\nFor Matrix 1:\n");

acceptMatrix(rows1, cols1, matrix1);

// Accept elements for the second matrix

printf("\nFor Matrix 2:\n");

acceptMatrix(rows2, cols2, matrix2);

// Check and print whether matrices are equal or not

if (areMatricesEqual(rows1, cols1, matrix1, rows2, cols2, matrix2)) {

printf("\nMatrices are equal.\n");

} else {

printf("\nMatrices are not equal.\n");

return 0;

q38

#include <stdio.h>

// Function to insert a number in the array at a given position

void insertNumber(int arr[], int *size, int position, int number) {

if (position < 0 || position > *size) {

printf("Invalid position for insertion.\n");

return;

}
// Shift elements to the right to make space for the new number

for (int i = *size; i > position; i--) {

arr[i] = arr[i - 1];

// Insert the number at the specified position

arr[position] = number;

// Increase the size of the array

(*size)++;

int main() {

int size, position, number;

// Get the size of the array from the user

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

scanf("%d", &size);

int array[size];

// Get array elements from the user

printf("Enter the array elements:\n");

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

scanf("%d", &array[i]);

// Get the position and number to insert from the user

printf("Enter the position to insert the number: ");

scanf("%d", &position);
printf("Enter the number to insert: ");

scanf("%d", &number);

// Insert the number at the specified position

insertNumber(array, &size, position, number);

// Print the modified array

printf("Modified Array after Insertion:\n");

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

printf("%d ", array[i]);

printf("\n");

return 0;

#include <stdio.h>

// Function to remove a number in the array from a given position

void removeNumber(int arr[], int *size, int position) {

if (position < 0 || position >= *size) {

printf("Invalid position for removal.\n");

return;

// Shift elements to the left to fill the gap

for (int i = position; i < *size - 1; i++) {

arr[i] = arr[i + 1];

}
// Decrease the size of the array

(*size)--;

int main() {

int size, position;

// Get the size of the array from the user

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

scanf("%d", &size);

int array[size];

// Get array elements from the user

printf("Enter the array elements:\n");

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

scanf("%d", &array[i]);

// Get the position to remove from the user

printf("Enter the position to remove the number: ");

scanf("%d", &position);

// Remove the number at the specified position

removeNumber(array, &size, position);

// Print the modified array

printf("Modified Array after Removal:\n");

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

printf("%d ", array[i]);

}
printf("\n");

return 0;

q39

#include <stdio.h>

// Function to swap two arrays

void swapArrays(int arr1[], int size1, int arr2[], int size2) {

// Swap the elements of the arrays

for (int i = 0; i < size1 && i < size2; i++) {

int temp = arr1[i];

arr1[i] = arr2[i];

arr2[i] = temp;

// Function to check if two arrays are equal

int areArraysEqual(int arr1[], int size1, int arr2[], int size2) {

if (size1 != size2) {

return 0; // Arrays have different sizes

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

if (arr1[i] != arr2[i]) {

return 0; // Arrays are not equal

}
return 1; // Arrays are equal

int main() {

int size1, size2;

// Get the size of the first array from the user

printf("Enter the size of the first array: ");

scanf("%d", &size1);

int array1[size1];

// Get elements for the first array from the user

printf("Enter elements for the first array:\n");

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

scanf("%d", &array1[i]);

// Get the size of the second array from the user

printf("Enter the size of the second array: ");

scanf("%d", &size2);

int array2[size2];

// Get elements for the second array from the user

printf("Enter elements for the second array:\n");

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

scanf("%d", &array2[i]);

// Swap the arrays


swapArrays(array1, size1, array2, size2);

// Print the swapped arrays

printf("\nAfter Swapping:\n");

printf("First Array: ");

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

printf("%d ", array1[i]);

printf("\n");

printf("Second Array: ");

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

printf("%d ", array2[i]);

printf("\n");

// Check and print whether arrays are equal or not

if (areArraysEqual(array1, size1, array2, size2)) {

printf("\nBoth arrays are equal.\n");

} else {

printf("\nArrays are not equal.\n");

return 0;

q40

#include <stdio.h>

#include <string.h>
// Function to swap two strings

void swapStrings(char str1[], char str2[]) {

char temp[100]; // Assuming a maximum length of 100 characters for each string

// Copy the content of the first string to a temporary string

strcpy(temp, str1);

// Copy the content of the second string to the first string

strcpy(str1, str2);

// Copy the content of the temporary string to the second string

strcpy(str2, temp);

int main() {

char string1[100], string2[100];

// Get the first string from the user

printf("Enter the first string: ");

fgets(string1, sizeof(string1), stdin);

// Remove newline character if present

size_t len1 = strlen(string1);

if (len1 > 0 && string1[len1 - 1] == '\n') {

string1[len1 - 1] = '\0';

// Get the second string from the user

printf("Enter the second string: ");

fgets(string2, sizeof(string2), stdin);


// Remove newline character if present

size_t len2 = strlen(string2);

if (len2 > 0 && string2[len2 - 1] == '\n') {

string2[len2 - 1] = '\0';

// Swap the strings

swapStrings(string1, string2);

// Print the swapped strings

printf("\nAfter Swapping:\n");

printf("First String: %s\n", string1);

printf("Second String: %s\n", string2);

return 0;

q41

#include <stdio.h>

// Function to perform bubble sort on an array

void bubbleSort(int arr[], int n) {

int i, j, temp;

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

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

// Swap if the element found is greater than the next element

if (arr[j] > arr[j + 1]) {

temp = arr[j];

arr[j] = arr[j + 1];


arr[j + 1] = temp;

int main() {

int n;

// Get the number of elements from the user

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

scanf("%d", &n);

int arr[n];

// Get elements from the user

printf("Enter the elements:\n");

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

scanf("%d", &arr[i]);

// Perform bubble sort

bubbleSort(arr, n);

// Print the sorted array

printf("\nSorted Array:\n");

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

printf("%d ", arr[i]);

printf("\n");
return 0;

q42

#include <stdio.h>

// Function to perform selection sort on an array

void selectionSort(int arr[], int n) {

int i, j, minIndex, temp;

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

// Assume the current index is the minimum

minIndex = i;

// Find the minimum element in the unsorted part of the array

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

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the current element

temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;

int main() {

int n;
// Get the number of elements from the user

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

scanf("%d", &n);

int arr[n];

// Get elements from the user

printf("Enter the elements:\n");

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

scanf("%d", &arr[i]);

// Perform selection sort

selectionSort(arr, n);

// Print the sorted array

printf("\nSorted Array:\n");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

q43

#include <stdio.h>

// Function to perform linear search


int linearSearch(int arr[], int n, int key) {

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

if (arr[i] == key) {

return i; // Return the index where the element is found

return -1; // Return -1 if the element is not found

// Function to find the largest element in an array

int findLargestElement(int arr[], int n) {

int max = arr[0];

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

if (arr[i] > max) {

max = arr[i];

return max;

int main() {

int n, key;

// Get the number of elements from the user

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

scanf("%d", &n);

int arr[n];
// Get elements from the user

printf("Enter the elements:\n");

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

scanf("%d", &arr[i]);

// Get the element to search from the user

printf("Enter the element to search: ");

scanf("%d", &key);

// Perform linear search

int index = linearSearch(arr, n, key);

// Check and print the result of linear search

if (index != -1) {

printf("Element %d found at index %d.\n", key, index);

} else {

printf("Element %d not found in the list.\n", key);

// Find and print the largest element in the array

int largestElement = findLargestElement(arr, n);

printf("Largest element in the array: %d\n", largestElement);

return 0;

q44

#include <stdio.h>
// Function to find duplicate elements in an array

void findDuplicates(int arr[], int n) {

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

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

// Compare each element with all other elements

if (arr[i] == arr[j]) {

printf("Duplicate element: %d\n", arr[i]);

int main() {

int n;

// Get the number of elements from the user

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

scanf("%d", &n);

int arr[n];

// Get elements from the user

printf("Enter the elements:\n");

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

scanf("%d", &arr[i]);

// Find and print duplicate elements

printf("\nDuplicate Elements:\n");

findDuplicates(arr, n);
return 0;

q45

#include <stdio.h>

// Function to insert an element into an array at a specific position

void insertElement(int arr[], int *size, int position, int element) {

if (position < 0 || position > *size) {

printf("Invalid position for insertion.\n");

return;

// Shift elements to the right to make space for the new element

for (int i = *size; i > position; i--) {

arr[i] = arr[i - 1];

// Insert the element at the specified position

arr[position] = element;

// Increase the size of the array

(*size)++;

int main() {

int size, position, element;

// Get the size of the array from the user


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

scanf("%d", &size);

int arr[size];

// Get array elements from the user

printf("Enter the array elements:\n");

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

scanf("%d", &arr[i]);

// Get the position and element to insert from the user

printf("Enter the position to insert the element: ");

scanf("%d", &position);

printf("Enter the element to insert: ");

scanf("%d", &element);

// Insert the element at the specified position

insertElement(arr, &size, position, element);

// Print the modified array

printf("\nModified Array after Insertion:\n");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

You might also like