BCA2CJ101 - Fundamentals of Programming (C Language)
Module V : Hands-on Problem-Solving Using C Practical Applications, Case Study and Course Project
MOHAMED JABIR, ASSISTANT PROFESSOR
SEMESTER II BCA DEPARTMENT OF COMPUTER SCIENCE
MAJLIS COLLEGE AUTONOMOUS
1. Variables, Data types, Constants and Operators:
1. Evaluation of expression ex: ((x+y) ^2 * (x+z))/w
Algorithm:
2. Start
3. Input values of XXX, YYY, ZZZ, and WWW.
4. Compute (X+Y)2(X + Y)^2(X+Y)2.
5. Compute (X+Z)(X + Z)(X+Z).
6. Multiply the results from steps 3 and 4.
7. Divide the result by WWW.
8. Output the final result.
9. End
C Program to Evaluate the Expression:
#include <stdio.h>
int main() {
float X, Y, Z, W, result;
printf("Enter values for X, Y, Z, and W: ");
scanf("%f %f %f %f", &X, &Y, &Z, &W);
if (W == 0) {
printf("Error! Division by zero is not allowed.\n");
return 1;
result = ((X + Y) * (X + Y) * (X + Z)) / W;
printf("The result of the expression is: %.2f\n", result);
return 0;
Sample Output:
Enter values for X, Y, Z, and W: 2 3 4 5
The result of the expression is: 14.00
2. Temperature conversion problem (Fahrenheit to Celsius)
Algorithm:
1. Start
2. Input the temperature in Fahrenheit (F).
3. Compute the temperature in Celsius using the formula C=(F-32) x 5
4. Output the temperature in Celsius. 9
5. End
C Program for Fahrenheit to Celsius Conversion:
#include <stdio.h>
int main() {
float fahrenheit, celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) * 5 / 9;
printf("Temperature in Celsius: %.2f°C\n", celsius);
return 0;
Sample Output:
Enter temperature in Fahrenheit: 98.6
Temperature in Celsius: 37.00°C
3. Program to convert days to months and days (Ex: 364 days =12 months and 4 days)
Algorithm:
1. Start
2. Input the number of days (D).
3. Compute the number of months: M=D/30
(Assuming 1 month = 30 days for simplicity)
4. Compute the remaining days: R=D%30
5. Output the number of months and remaining days.
6. End
Program:
#include <stdio.h>
int main() {
int days, months, remaining_days;
Input number of days
printf("Enter the number of days: ");
scanf("%d", &days);
Convert days to months and remaining days (assuming 1 month = 30 days)
months = days / 30;
remaining_days = days % 30;
printf("%d days = %d months and %d days\n", days, months, remaining_days);
return 0;
Sample Output:
Enter the number of days: 364
364 days = 12 months and 4 days
4. Salesman salary (Given: Basic Salary, Bonus for every item sold, commission on the
total monthly sales)
Algorithm:
1. Start
2. Input the following values:
Basic Salary
Number of items sold
Bonus per item sold
Total monthly sales amount
Commission percentage
3. Compute the Total Bonus:
Total Bonus=Number of items sold×Bonus per item
4. Compute the Commission:
Commission = (Commission Percentage) x Total Monthly Sales
100
5. Compute the Total Salary:
Total Salary=Basic Salary + Total Bonus + Commission
6. Output the Total Salary.
7. End
Program:
#include <stdio.h>
int main() {
float basic_salary, bonus_per_item, total_sales, commission_percentage;
int items_sold;
float total_bonus, commission, total_salary;
printf("Enter Basic Salary: ");
scanf("%f", &basic_salary);
printf("Enter Number of Items Sold: ");
scanf("%d", &items_sold);
printf("Enter Bonus per Item Sold: ");
scanf("%f", &bonus_per_item);
printf("Enter Total Monthly Sales: ");
scanf("%f", &total_sales);
printf("Enter Commission Percentage: ");
scanf("%f", &commission_percentage);
total_bonus = items_sold * bonus_per_item;
commission = (commission_percentage / 100) * total_sales;
total_salary = basic_salary + total_bonus + commission;
printf("Total Salary = %.2f\n", total_salary);
return 0;
}
Sample Output:
Enter Basic Salary: 20000
Enter Number of Items Sold: 50
Enter Bonus per Item Sold: 200
Enter Total Monthly Sales: 100000
Enter Commission Percentage: 5
Total Salary = 25500.00
2. Decision making (Branch / Loop) Statements:
5. Solution of quadratic equation
Algorithm:
A quadratic equation is of the form:
ax2+bx+c=0
Where a, b, and c are coefficients. The roots of the equation are given by the quadratic
formula: x= −b± √b2−4ac
2a
1. Start
2. Input values for a,b,c.
3. Compute the discriminant:
D=b2−4ac
4. Check the value of the discriminant:
If D>0: Two distinct real roots exist.
If D=0: One real root (both roots are equal).
If D<0: No real roots (complex roots exist).
5. Compute the roots using the quadratic formula if D≥0, otherwise compute complex roots.
6. Output the roots.
7. End
Program:
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
if (a == 0) {
printf("Error! 'a' cannot be zero in a quadratic equation.\n");
return 1;
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
// Two distinct real roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct:\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
printf("Roots are real and equal:\n");
printf("Root = %.2f\n", root1);
} else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary:\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
} return 0;
}
Sample Output:
Enter coefficients a, b, and c: 1 -3 2
Roots are real and distinct:
Root 1 = 2.00
Root 2 = 1.00
6. Maximum of three numbers
1. Start
2. Input three numbers: num1, num2, and num3.
3. Compare the numbers using conditional statements:
If num1 is greater than num2 and num3, then num1 is the largest.
Else if num2 is greater than num1 and num3, then num2 is the largest.
Otherwise, num3 is the largest.
4. Output the maximum number.
5. End
Program:
#include <stdio.h>
int main() {
float num1, num2, num3, max;
printf("Enter three numbers: ");
scanf("%f %f %f", &num1, &num2, &num3);
if (num1 >= num2 && num1 >= num3)
max = num1;
else if (num2 >= num1 && num2 >= num3)
max = num2;
else
max = num3;
printf("The maximum number is: %.2f\n", max);
return 0;
}
Sample Outputs:
Enter three numbers: 10 25 15
The maximum number is: 25.00
7. Calculate Square root of five numbers (using goto statement)
Algorithm:
1. Start
2. Initialize a counter (i = 1).
3. Use a goto label (input_numbers) to read a number.
4. Compute the square root using sqrt() function.
5. Display the result.
6. Increment the counter. If i ≤ 5, go back to input_numbers.
7. End
Program:
#include <stdio.h>
#include <math.h>
int main() {
int i = 1;
float num, result;
input_numbers: // Label for goto
if (i <= 5) {
printf("Enter number %d: ", i);
scanf("%f", &num);
if (num < 0) {
printf("Error: Square root of a negative number is not real.\n");
} else {
result = sqrt(num);
printf("Square root of %.2f = %.2f\n", num, result);
i++;
goto input_numbers;
return 0;
}
Sample Output:
Enter number 1: 16
Square root of 16.00 = 4.00
Enter number 2: 25
Square root of 25.00 = 5.00
Enter number 3: 9
Square root of 9.00 = 3.00
Enter number 4: -4
Error: Square root of a negative number is not real.
Enter number 5: 2.25
Square root of 2.25 = 1.50
8. Pay-Bill Calculation for different levels of employee (Switch statement)
Algorithm:
1. Start
2. Input employee level (1, 2, 3, or 4).
3. Use switch statement to determine the salary based on the level:
Level 1: Basic salary = 50,000
Level 2: Basic salary = 75,000
Level 3: Basic salary = 100,000
Level 4: Basic salary = 150,000
4. Apply Allowances and Deductions:
House Rent Allowance (HRA) = 20% of basic salary
Dearness Allowance (DA) = 50% of basic salary
Provident Fund (PF) = 12% of basic salary
Tax = 10% of (Basic Salary + HRA + DA)
5. Compute Net Salary using:
Net Salary=Basic Salary+HRA+DA−(PF+Tax)
6. Display the salary details.
7. End
Program:
#include <stdio.h>
int main() {
int level;
float basic_salary, hra, da, pf, tax, net_salary;
printf("Enter Employee Level (1-4): ");
scanf("%d", &level);
switch(level) {
case 1:
basic_salary = 50000;
break;
case 2:
basic_salary = 75000;
break;
case 3:
basic_salary = 100000;
break;
case 4:
basic_salary = 150000;
break;
default:
printf("Invalid level! Please enter a level between 1 and 4.\n");
return 1;
hra = 0.20 * basic_salary; // 20% House Rent Allowance
da = 0.50 * basic_salary; // 50% Dearness Allowance
pf = 0.12 * basic_salary; // 12% Provident Fund
tax = 0.10 * (basic_salary + hra + da); // 10% Tax on total salary
net_salary = basic_salary + hra + da - (pf + tax);
printf("\nSalary Breakdown for Level %d Employee:\n", level);
printf("Basic Salary: %.2f\n", basic_salary);
printf("HRA (20%%): %.2f\n", hra);
printf("DA (50%%): %.2f\n", da);
printf("PF Deduction (12%%): %.2f\n", pf);
printf("Tax Deduction (10%% of total salary): %.2f\n", tax);
printf("Net Salary: %.2f\n", net_salary);
return 0;
Sample Output:
Enter Employee Level (1-4): 2
Salary Breakdown for Level 2 Employee:
Basic Salary: 75000.00
HRA (20%): 15000.00
DA (50%): 37500.00
PF Deduction (12%): 9000.00
Tax Deduction (10% of total salary): 12750.00
Net Salary: 105750.00
9. Fibonacci series
Algorithm:
1. Start
2. Input the number of terms (n).
3. Initialize variables:
first = 0, second = 1
4. Print the first two terms.
5. Use a loop to calculate the next terms:
next = first + second
Update first = second and second = next
Print next
6. Repeat the loop until n terms are printed.
7. End
Program:
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive number.\n");
return 1;
printf("Fibonacci Series: ");
for (i = 1; i <= n; i++) {
printf("%d ", first);
next = first + second;
first = second;
second = next;
printf("\n");
return 0;
Sample Output:
Enter the number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
10. Armstrong numbers
Algorithm:
1. Start
2. Input a number (num).
3. Count the number of digits in num.
4. Extract each digit and compute its power raised to the number of digits.
5. Sum up these powered values.
6. If the sum equals num, it is an Armstrong number; otherwise, it is not.
7. Output the result.
8. End
Program:
#include <stdio.h>
#include <math.h>
int main() {
int num, originalNum, remainder, n = 0;
double result = 0;
printf("Enter a number: ");
scanf("%d", &num);
originalNum = num;
int temp = num;
while (temp != 0) {
temp /= 10;
n++;
temp = num;
while (temp != 0) {
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
if ((int)result == originalNum)
printf("%d is an Armstrong number.\n", originalNum);
else
printf("%d is not an Armstrong number.\n", originalNum);
return 0;
Sample Outputs:
Enter a number: 153
153 is an Armstrong number.
11. Pascal ‘s Triangle
Algorithm:
1. Start
2. Input the number of rows (n).
3. Use a nested loop to compute values:
Outer loop for rows (i = 0 to n-1).
Inner loop for columns (j = 0 to i).
Compute C(i, j) = i! / (j! * (i-j)!).
4. Display the values in a triangular format.
5. End
Program:
#include <stdio.h>
long long factorial(int num) {
long long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
return fact;
long long binomialCoeff(int n, int k) {
return factorial(n) / (factorial(k) * factorial(n - k));
void printPascalsTriangle(int rows) {
for (int i = 0; i < rows; i++) {
// Print leading spaces for alignment
for (int space = 0; space < rows - i - 1; space++)
printf(" ");
for (int j = 0; j <= i; j++)
printf("%4lld ", binomialCoeff(i, j));
printf("\n");
}
}
int main() {
int rows;
printf("Enter the number of rows for Pascal's Triangle: ");
scanf("%d", &rows);
printPascalsTriangle(rows);
return 0;
3. Arrays, Functions and Strings:
12. Prime numbers in an array
Algorithm:
1. Input the Array:
Read the array of integers.
2. Prime Check Function:
For each element in the array, check if it is a prime number.
A prime number is a number greater than 1 that has no divisors other than 1
and itself.
Steps to check if a number is prime:
If the number is less than or equal to 1, it's not prime.
For numbers greater than 1, check divisibility from 2 up to the square root of
the number.
If the number is divisible by any of these, it's not prime; otherwise, it is.
3. Display Prime Numbers:
For each number in the array, if it is a prime, print or store it.
4. End.
Program:
#include <stdio.h>
#include <math.h>
int isPrime(int num) {
if (num <= 1) {
return 0; // Not a prime number
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; // Not a prime number
return 1; // Prime number
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array: \n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
printf("Prime numbers in the array are: \n");
for (int i = 0; i < n; i++) {
if (isPrime(arr[i])) {
printf("%d ", arr[i]);
return 0;
Sample Output:
Enter the number of elements in the array: 7
Enter the elements of the array:
10 23 4 17 6 11 9
Prime numbers in the array are:
23 17 11
13. Sorting data (Ascending and Descending)
Algorithm:
1. Input the Array:
Read the array of integers.
2. Sort the Array in Ascending Order:
Use a sorting algorithm (like Bubble Sort or Selection Sort) to sort the array in
increasing order.
Compare each element with the next one and swap them if necessary to ensure
the smallest elements move to the front.
3. Sort the Array in Descending Order:
Similarly, modify the sorting logic to sort the array in decreasing order (by
comparing and swapping the elements such that the largest element moves to
the front).
4. Display the Sorted Arrays:
Print the array in ascending order.
Print the array in descending order.
5. End.
Program:
#include <stdio.h>
void sortAscending(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
void sortDescending(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
void displayArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
printf("\n");
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sortAscending(arr, n);
printf("Array in Ascending Order: ");
displayArray(arr, n);
sortDescending(arr, n);
printf("Array in Descending Order: ");
displayArray(arr, n);
return 0;
}
Sample Output:
Enter the number of elements in the array: 6
Enter the elements of the array:
12 7 3 18 5 1
Array in Ascending Order: 1 3 5 7 12 18
Array in Descending Order: 18 12 7 5 3 1
14. Matrix Addition and Subtraction
Algorithm:
1. Input the Matrices:
Read the number of rows (m) and columns (n) for two matrices.
Read the elements of both matrices.
2. Matrix Addition:
For each element of the matrices, sum the corresponding elements from both
matrices.
Store the result in a new matrix.
3. Matrix Subtraction:
For each element of the matrices, subtract the corresponding elements of the
second matrix from the first matrix.
Store the result in another matrix.
4. Display the Results:
Print the resulting matrices after addition and subtraction.
Program:
#include <stdio.h>
void addMatrices(int matrix1[][10], int matrix2[][10], int result[][10], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
void subtractMatrices(int matrix1[][10], int matrix2[][10], int result[][10], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
void displayMatrix(int matrix[][10], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
printf("\n");
int main() {
int m, n;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
int matrix1[10][10], matrix2[10][10], resultAdd[10][10], resultSub[10][10];
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix1[i][j]);
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix2[i][j]);
addMatrices(matrix1, matrix2, resultAdd, m, n);
printf("\nMatrix Addition Result:\n");
displayMatrix(resultAdd, m, n);
subtractMatrices(matrix1, matrix2, resultSub, m, n);
printf("\nMatrix Subtraction Result:\n");
displayMatrix(resultSub, m, n);
return 0;
Sample Input and Output:
Enter the number of rows and columns: 2 3
Enter elements of the first matrix:
123
456
Enter elements of the second matrix:
654
321
Matrix Addition Result:
777
777
Matrix Subtraction Result:
-5 -3 -1
135
15. Matrix Multiplication
Algorithm:
1. Input the matrices:
Matrix A should have dimensions m x n.
Matrix B should have dimensions n x p.
2. Matrix Multiplication:
Perform the multiplication as described above and store the result in the
resulting matrix C.
3. Display the Result:
Print the resulting matrix.
Program:
#include <stdio.h>
void multiplyMatrices(int A[][10], int B[][10], int C[][10], int m, int n, int p) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
void displayMatrix(int matrix[][10], int m, int p) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
printf("%d ", matrix[i][j]);
printf("\n");
int main() {
int m, n, p;
printf("Enter the number of rows and columns for Matrix A: ");
scanf("%d %d", &m, &n);
int A[10][10];
printf("Enter elements of Matrix A:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &A[i][j]);
}
printf("Enter the number of columns for Matrix B: ");
scanf("%d", &p);
int B[10][10];
printf("Enter elements of Matrix B:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
scanf("%d", &B[i][j]);
int C[10][10];
multiplyMatrices(A, B, C, m, n, p);
printf("Resultant Matrix after multiplication:\n");
displayMatrix(C, m, p);
return 0;
Sample Input and Output:
Enter the number of rows and columns for Matrix A: 2 3
Enter elements of Matrix A:
123
456
Enter the number of columns for Matrix B: 2
Enter elements of Matrix B:
78
9 10
11 12
Resultant Matrix after multiplication:
58 64
139 154
16. Transpose of a matrix
Algorithm:
1. Input the matrix:
Read the number of rows and columns for the matrix.
Read the elements of the matrix.
2. Transpose the matrix:
Swap the rows and columns to obtain the transpose.
3. Display the result:
Print the transposed matrix.
Program:
#include <stdio.h>
void transposeMatrix(int matrix[][10], int transpose[][10], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transpose[j][i] = matrix[i][j]; // Swap rows and columns
void displayMatrix(int matrix[][10], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
printf("\n");
int main() {
int m, n;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &m, &n);
int matrix[10][10], transpose[10][10];
printf("Enter elements of the matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
transposeMatrix(matrix, transpose, m, n);
printf("\nTransposed Matrix:\n");
displayMatrix(transpose, n, m);
return 0;
Sample Input and Output:
Enter the number of rows and columns: 2 3
Enter elements of the matrix:
123
456
Transposed Matrix:
14
25
36
17. Function with no arguments and no return value
Algorithm:
1. Start.
2. Define the function that does not take any arguments and does not return any
value:
This function will print a message or perform a specific task.
3. In the main function:
Call the defined function.
4. Display output (if the function is used for output).
5. End.
Program:
#include <stdio.h>
void displayMessage() {
printf("Hello, welcome to the world of C programming!\n");
int main() {
displayMessage();
return 0;
Sample Output:
Hello, welcome to the world of C programming!
18. Functions with argument and return value
Algorithm:
1. Start.
The function takes two integers as arguments.
The function returns the sum of these two integers.
2. In the main function:
Declare two integers to hold the numbers that will be added.
Read these two integers from the user.
Call the add function and pass the numbers as arguments.
Store the return value of the function in a variable.
Print the result to the screen.
3. End.
Program:
#include <stdio.h>
int add(int a, int b) {
return a + b;
int main() {
int num1, num2, result;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
result = add(num1, num2);
printf("The sum of %d and %d is: %d\n", num1, num2, result);
return 0;
Sample Input and Output:
Enter first number: 12
Enter second number: 8
The sum of 12 and 8 is: 20
19. Functions with argument and multiple return values
Algorithm:
1. Start.
2. Define a function that:
Takes arguments and pointers to variables where the results will be stored.
Performs calculations and stores the results at the provided memory locations.
3. In the main function:
Declare variables and pass them by reference (using pointers) to the function.
Print the values after the function call.
4. End.
Program:
#include <stdio.h>
void calculate(int a, int b, int *sum, int *difference) {
*sum = a + b;
*difference = a - b;
}
int main() {
int num1, num2, sum, difference;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
calculate(num1, num2, &sum, &difference);
printf("The sum of %d and %d is: %d\n", num1, num2, sum);
printf("The difference between %d and %d is: %d\n", num1, num2, difference);
return 0;
Sample Input and Output:
Enter first number: 10
Enter second number: 5
The sum of 10 and 5 is: 15
The difference between 10 and 5 is: 5
20. Function that convert lower case letters to upper case
Algorithm:
1. Start.
2. Define a function toUpperCase that:
Takes a character as input.
If the character is a lowercase letter ('a' to 'z'), converts it to the corresponding
uppercase letter ('A' to 'Z').
If the character is already uppercase or not a letter, it returns the character
unchanged.
3. In the main function:
Read a character from the user.
Call the toUpperCase function to convert the character.
Print the converted character.
4. End.
Program:
#include <stdio.h>
char toUpperCase(char c) {
if (c >= 'a' && c <= 'z') {
return c - 'a' + 'A';
return c;
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
char result = toUpperCase(ch);
printf("The converted character is: %c\n", result);
return 0;
Sample Input and Output:
Enter a character: g
The converted character is: G
21. Factorial using recursion.
1. Start.
2. Define a recursive function factorial that:
If n == 0, return 1 (base case).
Otherwise, return n * factorial(n - 1).
3. In the main function:
Read an integer n from the user.
Call the factorial function and store the result.
Print the result.
4. End.
Program:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
int main() {
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
result = factorial(num);
printf("Factorial of %d is: %d\n", num, result);
return 0;
Sample Input and Output:
Enter a number: 5
Factorial of 5 is: 120
22. Perform String Operations using Switch Case
Algorithm:
1. Start.
2. Define a switch-case menu that:
Prompt the user to choose a string operation (concatenate, length, compare, copy).
Based on the input choice, perform the corresponding string operation.
3. In the main function:
Take user input for the operation choice.
Perform the appropriate string operation using a switch-case structure.
4. End.
Program:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
int choice;
do {
printf("\nString Operations Menu:\n");
printf("1. Concatenate\n");
printf("2. Find Length\n");
printf("3. Compare Strings\n");
printf("4. Copy String\n");
printf("5. Exit\n");
printf("Enter your choice (1-5): ");
scanf("%d", &choice);
getchar();
switch(choice) {
case 1:
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0';
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0';
strcpy(result, str1);
strcat(result, str2);
printf("Concatenated string: %s\n", result);
break;
case 2:
printf("Enter a string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0';
printf("Length of the string: %lu\n", strlen(str1));
break;
case 3:
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0';
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = '\0';
if (strcmp(str1, str2) == 0) {
printf("The strings are identical.\n");
} else {
printf("The strings are different.\n");
break;
case 4:
printf("Enter the source string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = '\0';
strcpy(str2, str1);
printf("The copied string is: %s\n", str2);
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
} while(choice != 5);
return 0; }
Sample Input and Output: 1
String Operations Menu:
1. Concatenate
2. Find Length
3. Compare Strings
4. Copy String
5. Exit
Enter your choice (1-5): 1
Enter the first string: Hello
Enter the second string: World
Concatenated string: HelloWorld
Sample Input and Output: 2
String Operations Menu:
1. Concatenate
2. Find Length
3. Compare Strings
4. Copy String
5. Exit
Enter your choice (1-5): 3
Enter the first string: Hello
Enter the second string: hello
The strings are different.
23. Largest among a set of numbers using command line argument.
Algorithm:
1. Start.
2. Check the number of arguments: If argc is less than 2, print an error message (because
we need at least one number to compare).
3. Loop through all arguments: Convert each argument from string to integer and
compare it with the current largest number.
4. Print the largest number.
5. End.
6.
Program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Error: Please provide numbers as command line arguments.\n");
return 1;
int largest = atoi(argv[1]); largest
for (int i = 2; i < argc; i++) {
int num = atoi(argv[i]);
if (num > largest) {
largest = num;
printf("The largest number is: %d\n", largest);
return 0;
Sample Input and Output:
./largest_number 12 45 23 78 56
The largest number is: 78
4. Structures and Union:
24. Structure that describes a hotel (name, address, grade, avg room rent, number of rooms)
Perform some operations (list of hotels of a given grade etc.)
Algorithm:
1. Start.
2. Define a Hotel structure.
3. Initialize a list of hotels.
4. Create functions for:
Adding a hotel.
Displaying all hotels.
Listing hotels of a specific grade.
5. End.
Program:
#include <stdio.h>
#include <string.h>
struct Hotel {
char name[100];
char address[200];
char grade;
float avg_room_rent;
int num_rooms;
};
void addHotel(struct Hotel hotels[], int *count) {
struct Hotel newHotel;
printf("Enter hotel name: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter hotel address: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter hotel grade (A/B/C): ");
scanf(" %c", &[Link]);
printf("Enter average room rent: ");
scanf("%f", &newHotel.avg_room_rent);
printf("Enter number of rooms: ");
scanf("%d", &newHotel.num_rooms);
getchar();
hotels[*count] = newHotel;
(*count)++;
void displayAllHotels(struct Hotel hotels[], int count) {
if (count == 0) {
printf("No hotels available.\n");
return;
printf("\nList of all hotels:\n");
for (int i = 0; i < count; i++) {
printf("\nHotel Name: %s\n", hotels[i].name);
printf("Address: %s\n", hotels[i].address);
printf("Grade: %c\n", hotels[i].grade);
printf("Average Room Rent: %.2f\n", hotels[i].avg_room_rent);
printf("Number of Rooms: %d\n", hotels[i].num_rooms);
void listHotelsByGrade(struct Hotel hotels[], int count, char grade) {
int found = 0;
printf("\nHotels with grade '%c':\n", grade);
for (int i = 0; i < count; i++) {
if (hotels[i].grade == grade) {
printf("\nHotel Name: %s\n", hotels[i].name);
printf("Address: %s\n", hotels[i].address);
printf("Average Room Rent: %.2f\n", hotels[i].avg_room_rent);
printf("Number of Rooms: %d\n", hotels[i].num_rooms);
found = 1;
if (!found) {
printf("No hotels found with grade '%c'.\n", grade);
int main() {
struct Hotel hotels[50];
int count = 0;
int choice;
do {
printf("\nHotel Management System\n");
printf("1. Add a new hotel\n");
printf("2. Display all hotels\n");
printf("3. List hotels by grade\n");
printf("4. Exit\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
getchar();
switch(choice) {
case 1:
addHotel(hotels, &count);
break;
case 2:
displayAllHotels(hotels, count);
break;
case 3:
char grade;
printf("Enter the grade (A/B/C): ");
scanf(" %c", &grade);
listHotelsByGrade(hotels, count, grade);
break;
case 4:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
} while (choice != 4);
return 0;
Sample Input and Output:
Hotel Management System
1. Add a new hotel
2. Display all hotels
3. List hotels by grade
4. Exit
Enter your choice (1-4): 1
Enter hotel name: Grand Palace
Enter hotel address: 123 Royal Street
Enter hotel grade (A/B/C): A
Enter average room rent: 200.50
Enter number of rooms: 100
Hotel Management System
1. Add a new hotel
2. Display all hotels
3. List hotels by grade
4. Exit
Enter your choice (1-4): 1
Enter hotel name: Sunset Resort
Enter hotel address: 45 Beach Road
Enter hotel grade (A/B/C): B
Enter average room rent: 150.75
Enter number of rooms: 50
Hotel Management System
1. Add a new hotel
2. Display all hotels
3. List hotels by grade
4. Exit
Enter your choice (1-4): 2
List of all hotels:
Hotel Name: Grand Palace
Address: 123 Royal Street
Grade: A
Average Room Rent: 200.50
Number of Rooms: 100
Hotel Name: Sunset Resort
Address: 45 Beach Road
Grade: B
Average Room Rent: 150.75
Number of Rooms: 50
Sample Output 2 (Listing Hotels by Grade):
Hotel Management System
1. Add a new hotel
2. Display all hotels
3. List hotels by grade
4. Exit
Enter your choice (1-4): 3
Enter the grade (A/B/C): A
Hotels with grade 'A':
Hotel Name: Grand Palace
Address: 123 Royal Street
Average Room Rent: 200.50
Number of Rooms: 100
25. Using Pointers in Structures.
Algorithm:
1. Define a structure to represent a hotel with attributes like name, address, grade,
avg_room_rent, and num_rooms.
2. Dynamically allocate memory for a structure using malloc.
3. Use a pointer to access and modify the structure.
4. Pass the pointer to a function to update or display the values.
5. End.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Hotel {
char name[100];
char address[200];
char grade;
float avg_room_rent;
int num_rooms;
};
void inputHotelDetails(struct Hotel *hotel) {
printf("Enter hotel name: ");
fgets(hotel->name, sizeof(hotel->name), stdin);
hotel->name[strcspn(hotel->name, "\n")] = '\0';
printf("Enter hotel address: ");
fgets(hotel->address, sizeof(hotel->address), stdin);
hotel->address[strcspn(hotel->address, "\n")] = '\0';
printf("Enter hotel grade (A/B/C): ");
scanf(" %c", &hotel->grade);
printf("Enter average room rent: ");
scanf("%f", &hotel->avg_room_rent);
printf("Enter number of rooms: ");
scanf("%d", &hotel->num_rooms);
getchar();
void displayHotelDetails(struct Hotel *hotel) {
printf("\nHotel Name: %s\n", hotel->name);
printf("Address: %s\n", hotel->address);
printf("Grade: %c\n", hotel->grade);
printf("Average Room Rent: %.2f\n", hotel->avg_room_rent);
printf("Number of Rooms: %d\n", hotel->num_rooms);
int main() {
struct Hotel *hotel1 = (struct Hotel *)malloc(sizeof(struct Hotel));
if (hotel1 == NULL) {
printf("Memory allocation failed!\n");
return 1;
inputHotelDetails(hotel1);
displayHotelDetails(hotel1);
free(hotel1);
return 0;
Sample Input and Output:
Enter hotel name: Royal Inn
Enter hotel address: 10 City Center
Enter hotel grade (A/B/C): A
Enter average room rent: 150.50
Enter number of rooms: 120
Hotel Name: Royal Inn
Address: 10 City Center
Grade: A
Average Room Rent: 150.50
Number of Rooms: 120
26. Cricket team details using Union
Algorithm:
1. Define a Player structure.
2. Define a CricketTeam structure containing player details.
3. Use a union for the player's stats, and access them based on the player's role.
4. Display the player’s details according to the role.
Program:
#include <stdio.h>
#include <string.h>
union PlayerStats {
float batting_avg;
float bowling_avg;
struct {
float batting_avg;
float bowling_avg;
} all_rounder_stats;
};
struct CricketPlayer {
char name[50];
char role[20];
union PlayerStats stats;
};
void inputPlayerDetails(struct CricketPlayer *player) {
printf("Enter player's name: ");
fgets(player->name, sizeof(player->name), stdin);
player->name[strcspn(player->name, "\n")] = '\0';
printf("Enter player's role (Batsman/Bowler/All-rounder): ");
fgets(player->role, sizeof(player->role), stdin);
player->role[strcspn(player->role, "\n")] = '\0';
if (strcmp(player->role, "Batsman") == 0) {
printf("Enter batting average: ");
scanf("%f", &player->stats.batting_avg);
} else if (strcmp(player->role, "Bowler") == 0) {
printf("Enter bowling average: ");
scanf("%f", &player->stats.bowling_avg);
} else if (strcmp(player->role, "All-rounder") == 0) {
printf("Enter batting average: ");
scanf("%f", &player->stats.all_rounder_stats.batting_avg);
printf("Enter bowling average: ");
scanf("%f", &player->stats.all_rounder_stats.bowling_avg);
} else {
printf("Invalid role.\n");
getchar();
void displayPlayerDetails(struct CricketPlayer *player) {
printf("\nPlayer Name: %s\n", player->name);
printf("Role: %s\n", player->role);
if (strcmp(player->role, "Batsman") == 0) {
printf("Batting Average: %.2f\n", player->stats.batting_avg);
} else if (strcmp(player->role, "Bowler") == 0) {
printf("Bowling Average: %.2f\n", player->stats.bowling_avg);
} else if (strcmp(player->role, "All-rounder") == 0) {
printf("Batting Average: %.2f\n", player->stats.all_rounder_stats.batting_avg);
printf("Bowling Average: %.2f\n", player->stats.all_rounder_stats.bowling_avg);
int main() {
struct CricketPlayer player;
inputPlayerDetails(&player);
displayPlayerDetails(&player);
return 0;
Sample Input and Output:
Enter player's name: Virat Kohli
Enter player's role (Batsman/Bowler/All-rounder): Batsman
Enter batting average: 55.5
Player Name: Virat Kohli
Role: Batsman
Batting Average: 55.50
Enter player's name: James Anderson
Enter player's role (Batsman/Bowler/All-rounder): Bowler
Enter bowling average: 26.7
Player Name: James Anderson
Role: Bowler
Bowling Average: 26.70
Enter player's name: Ben Stokes
Enter player's role (Batsman/Bowler/All-rounder): All-rounder
Enter batting average: 35.2
Enter bowling average: 31.4
Player Name: Ben Stokes
Role: All-rounder
Batting Average: 35.20
Bowling Average: 31.40
5. Pointers:
27. Evaluation of Pointer expressions
Algorithm:
1. Declare a pointer and initialize it to the address of an array.
2. Perform pointer arithmetic (e.g., pointer increment).
3. Dereference the pointer to access the value it points to.
4. Perform comparisons to evaluate which pointer points to a greater address.
5. Output the results of the pointer expressions.
Program:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer points to the first element of the array
printf("First element using pointer: %d\n", *ptr);
printf("Second element using pointer: %d\n", *(ptr + 1));
printf("Third element using pointer: %d\n", *(ptr + 2));
ptr++;
printf("After increment, pointer points to: %d\n", *ptr); // Points to arr[1] (20)
ptr--;
printf("After decrement, pointer points to: %d\n", *ptr);
int *ptr2 = arr + 4; // Pointer to the last element of the array (arr[4])
if (ptr < ptr2) {
printf("ptr points to a memory address less than ptr2\n");
if (ptr == arr) {
printf("ptr points to the first element of the array\n");
printf("Using pointer expression for last element: %d\n", *(arr + 4));
return 0;
Sample Output:
First element using pointer: 10
Second element using pointer: 20
Third element using pointer: 30
After increment, pointer points to: 20
After decrement, pointer points to: 10
ptr points to a memory address less than ptr2
ptr points to the first element of the array
Using pointer expression for last element: 50
28. Function to exchange two pointer values.
Algorithm:
1. Start
2. Declare two integer variables: a and b, and initialize them with some values.
3. Declare a function swapValues that takes two integer pointers as arguments.
4. Inside swapValues function:
Declare a temporary variable temp.
Assign the value pointed by the first pointer to temp.
Assign the value pointed by the second pointer to the first pointer.
Assign the value stored in temp to the second pointer.
5. In the main function:
Call the swapValues function with the addresses of a and b using the &
operator.
6. Display the values of a and b before and after the swap.
7. End
Program:
#include <stdio.h>
void swapValues(int *ptr1, int *ptr2) {
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
int main() {
int a = 10, b = 20;
printf("Before swapping:\n");
printf("a = %d, b = %d\n", a, b);
swapValues(&a, &b);
printf("\nAfter swapping:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
Sample Output:
Before swapping:
a = 10, b = 20
After swapping:
a = 20, b = 10
29. Reverse a string using pointers
Algorithm:
1. Start
2. Declare a string to be reversed. For example, char str[].
3. Initialize two pointers:
One pointer startPtr points to the beginning of the string (i.e., str).
The other pointer endPtr points to the last character of the string (i.e., str +
strlen(str) - 1).
4. Repeat the following steps while startPtr is less than endPtr:
Swap the values pointed to by startPtr and endPtr.
Move startPtr forward (increment it).
Move endPtr backward (decrement it).
5. End
Program:
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
char *startPtr = str;
char *endPtr = str + strlen(str) - 1;
while (startPtr < endPtr) {
char temp = *startPtr;
*startPtr = *endPtr;
*endPtr = temp;
startPtr++;
endPtr--;
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
Sample Output:
Enter a string: Hello, World!
Original string: Hello, World!
Reversed string: !dlroW ,olleH
30. Insertion, deletion, and searching in an array.
Algorithm for Insertion:
1. Start
2. Input the array size (n) and the array elements.
3. Input the element (ele) to be inserted and the position (pos) where it needs to be
inserted.
4. Check if the array is full. If it is full, print an error message and exit.
5. Shift the elements from position pos to the right to create space for the new element.
6. Insert the element ele at the specified position pos.
7. Increase the size of the array by 1.
8. Display the array after insertion.
9. End
Algorithm for Deletion:
1. Start
2. Input the array size (n) and the array elements.
3. Input the position (pos) of the element to be deleted.
4. Check if the array is empty or the position is invalid (greater than n). If it is, print an
error message and exit.
5. Shift the elements from position pos + 1 to the right to fill the gap left by the deleted
element.
6. Decrease the size of the array by 1.
7. Display the array after deletion.
8. End
Algorithm for Searching:
1. Start
2. Input the array size (n) and the array elements.
3. Input the element (target) to be searched.
4. Traverse the array from the beginning to the end.
5. Compare each element of the array with the target.
6. If a match is found, return the index of the element.
7. If the element is not found by the end of the array, return -1.
8. Display the result (index if found, -1 if not found).
9. End
Program:
#include <stdio.h>
#define MAX_SIZE 100
void insertElement(int arr[], int *size, int element, int position) {
if (*size >= MAX_SIZE) { // Check if array is full
printf("Array is full!\n");
return;
for (int i = *size; i >= position; i--) {
arr[i] = arr[i - 1];
arr[position - 1] = element;
(*size)++; // Increase the size of the array
void deleteElement(int arr[], int *size, int position) {
if (*size == 0) {
printf("Array is empty!\n");
return;
for (int i = position - 1; i < *size - 1; i++) {
arr[i] = arr[i + 1];
}
(*size)--;
int searchElement(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
return -1;
void displayArray(int arr[], int size) {
if (size == 0) {
printf("Array is empty.\n");
return;
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
printf("\n");
int main() {
int arr[MAX_SIZE];
int size = 5;
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
int choice, element, position, index, target;
while (1) {
printf("\nMenu:\n");
printf("1. Insert Element\n");
printf("2. Delete Element\n");
printf("3. Search Element\n");
printf("4. Display Array\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to insert: ");
scanf("%d", &element);
printf("Enter the position to insert the element: ");
scanf("%d", &position);
if (position < 1 || position > size + 1) {
printf("Invalid position! Please enter a position between 1 and %d.\n", size + 1);
} else {
insertElement(arr, &size, element, position);
printf("After insertion: ");
displayArray(arr, size);
break;
case 2:
printf("Enter the position to delete the element: ");
scanf("%d", &position);
if (position < 1 || position > size) {
printf("Invalid position! Please enter a position between 1 and %d.\n", size);
} else {
deleteElement(arr, &size, position);
printf("After deletion: ");
displayArray(arr, size);
break;
case 3:
printf("Enter the element to search: ");
scanf("%d", &target);
index = searchElement(arr, size, target);
if (index != -1) {
printf("Element %d found at index %d.\n", target, index);
} else {
printf("Element %d not found in the array.\n", target);
break;
case 4:
printf("Current Array: ");
displayArray(arr, size);
break;
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Please select a valid option.\n");
return 0;
}
Sample Output:
Menu:
1. Insert Element
2. Delete Element
3. Search Element
4. Display Array
5. Exit
Enter your choice: 4
Current Array: 10 20 30 40 50
Menu:
1. Insert Element
2. Delete Element
3. Search Element
4. Display Array
5. Exit
Enter your choice: 1
Enter the element to insert: 25
Enter the position to insert the element: 3
After insertion: 10 20 25 30 40 50
Menu:
1. Insert Element
2. Delete Element
3. Search Element
4. Display Array
5. Exit
Enter your choice: 3
Enter the element to search: 30
Element 30 found at index 2.
Menu:
1. Insert Element
2. Delete Element
3. Search Element
4. Display Array
5. Exit
Enter your choice: 2
Enter the position to delete the element: 3
After deletion: 10 20 40 50