NAME : Nandani
ENROLLMENT NUMBER : 2024MEB043
DEPARTMENT: MECHANICAL ENGINEERING
GROUP : 4
Problem 1: Compute Factorial Using Recursion
Problem Statement: Write a recursive function to compute the factorial of a given positive integer
n.
Function Prototype:
long computeFactorial(int n);
Requirements:
• The function should handle input validation (ensure n ≥ 0).
• The base case should return 1 when n == 0.
• Demonstrate the function with multiple test cases.
#include<stdio.h>
long computeFactorial(int n);
long computeFactorial(int n)
{
if(n==0)
return 1;
else
return n*computeFactorial(n-1);
int main()
int n;
long k;
printf("Enter the number : ");
scanf("%d",&n);
k = computeFactorial(n);
printf("The factorial is :%ld",k);
return 0;
Problem 2: Finding Maximum and Minimum in an Array Using Recursion
Problem Statement: Develop a recursive function to determine the maximum and minimum
elements in an
integer array.
Function Prototypes:
int findMax(int arr[], int n, int index, int maxVal);
int findMin(int arr[], int n, int index, int minVal);
#include<stdio.h>
int findMax(int arr[],int n,int index,int maxVal);
int findMin(int arr[],int n,int index,int minVal);
int findMax(int arr[],int n,int index,int maxVal)
{
if(index<n)
if(arr[index]>maxVal)
maxVal = arr[index];
index++;
findMax(arr,n,index,maxVal);
else
return maxVal;
int findMin(int arr[],int n,int index,int minVal)
if(index<n)
if(arr[index]<minVal)
{
minVal = arr[index];
index++;
findMin(arr,n,index,minVal);
else
return minVal;
int main()
int n,a,b,i,max,min;
printf("Enter the number of elements: ");
scanf("%d",&n);
int nums[n];
printf("ENTER ELEMENTS IS THE ARRAY");
for(i=0;i<n;i++)
{
scanf("%d",&nums[i]);
max=nums[0];
min = nums[0];
a=findMax(nums,n,0,max);
b=findMin(nums,n,0,min);
printf("MAXIMUM :%d\n",a);
printf("MINIMUM:%d\n",b);
return 0;
Problem 3: Reverse a String Using Recursion
Problem Statement: Implement a recursive function to reverse a given string.
Function Prototype:
void reverseString(char str[], int start, int end);
#include<stdio.h>
#define size 100
void reverseString(char st[],int start,int end);
void reverseString(char st[],int start,int end)
if(start<end)
char c;
c = st[start];
st[start] = st[end];
st[end] = c;
start++;
end--;
reverseString(st,start,end);
}
else
printf("The revesed string is : %s",st);
int main()
int i,l=0;
char st[size];
printf("Enter the sentence :");
scanf("%[^\n]s",st);
for(i=0;i<size;i++)
if(st[i]!='\0')
l++;
else
break;
}
reverseString(st,0,l-1);
Problem 5: Manage Student Records Using Structures
Problem Statement: Create a structure to store student records and display the student details.
Structure Definition:
struct Student {
char name[50];
int rollNo;
float marks;
};
Requirements:
• Accept input for a single student.
• Display student details in a formatted manner.
#include<stdio.h>
struct Student
char name[50];
int rollNo;
float marks;
};
int main()
struct Student c;
printf("Enter the student details :\n");
printf("Name : ");
scanf("%[^\n]s",c.name);
printf("Roll no :");
scanf("%d",&c.rollNo);
printf("Marks :");
scanf("%f",&c.marks);
printf("\nStudent details :\n");
printf("Name :%s\n",c.name);
printf("Roll no :%d\n",c.rollNo);
printf("Marks :%.2f",c.marks);
return 0;
Problem 6: Complex Number Operations Using Structures
Problem Statement: Implement addition and multiplication operations on complex numbers
using structures.
Structure Definition:
struct Complex {
float real;
float imag;
};
Requirements:
• Define functions to add and multiply two complex numbers.
• Take user input for two complex numbers and perform operations.
#include<stdio.h>
struct Complex
float real;
float imag;
};
struct Complex readComplex() {
struct Complex c;
printf("Enter real and imaginary part:");
scanf("%f %f",&c.real,&c.imag);
return c;
struct Complex addComplex(struct Complex c1,struct Complex c2)
struct Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
struct Complex multiplyComplex(struct Complex c1,struct Complex c2)
struct Complex result;
result.real = c1.real*c2.real - c1.imag*c2.imag;
result.imag = c1.real*c2.imag + c1.imag*c2.real;
return result;
void displayComplex(struct Complex c)
printf("%.1f + %.1fi",c.real,c.imag);
int main()
struct Complex c1,c2,sum,prod;
` printf("Enter the 1st complex number : \n");
c1 = readComplex();
printf("Enter the 2nd complex number :\n");
c2 = readComplex();
sum = addComplex(c1,c2);
prod = multiplyComplex(c1,c2);
printf("Sum :");
displayComplex(sum);
printf("\nProduct :");
displayComplex(prod);
return 0;}
Problem 7: Managing Multiple Student Records Using Arrays of Structures
Problem Statement: Modify the Student structure to handle multiple student records using an
array of structures.
Requirements:
• Accept details of n students.
• Display all records in a tabular format.
• Find and print the student with the highest marks.
#include<stdio.h>
#define size 50
struct Student
char name[size];
int rollno;
float marks;
};
int main()
int n,i,max=0,p=0;
printf("Enter the number of students :");
scanf("%d",&n);
struct Student Students[n];
for(i=0;i<n;i++)
printf("Enter the details for student %d:\n",i+1);
printf("Name :");
scanf("%s",Students[i].name);
printf("Roll no:");
scanf("%d",&Students[i].rollno);
printf("Marks :");
scanf("%f",&Students[i].marks);
printf("Student record :\n");
for(i=0;i<n;i++)
printf("%s (Roll no: %d) - Marks: %.2f
\n",Students[i].name,Students[i].rollno,Students[i].marks);
if(Students[i].marks>max)
max = Students[i].marks;
p =i;
printf("Topper : %s (Roll No : %d) - Marks:
%.2f",Students[p].name,Students[p].rollno,Students[p].marks);
return 0;
}
Problem 8: Employee Payroll System
Problem Statement: Develop an Employee Payroll System using structures, arrays of structures,
and recursion.
Structure Definition:
struct Employee {
char name[50];
int empID;
float salary;
};
Requirements:
• Accept details of multiple employees.
• Display all employee records in a formatted manner.
• Find the employee with the highest salary using recursion.
Recursive Function Prototype:
Employee findTopEarner(Employee arr[], int n, int index, Employee topEarner);
#include<stdio.h>
#define size 100
struct Employee
char name[size];
float salary;
int empID;
};
int main()
int n;
printf("Enter the number of employees :");
scanf("%d",&n);
struct Employee employees[n];
int i;
for(i=0;i<n;i++)
printf("Enter the details of the employee %d :\n",i+1);
printf("Name: ");
scanf("%s",employees[i].name);
printf("Employee ID: ");
scanf("%d",&employees[i].empID);
printf("Salary: ");
scanf("%f",&employees[i].salary);
printf("Employee records:\n");
int max=0,p=0;
for(i=0;i<n;i++)
printf("%s (ID: %d) - Salary: %.2f
\n",employees[i].name,employees[i].empID,employees[i].salary);
if(employees[i].salary>max)
max = employees[i].salary;
p =i;
}
printf("\nTop Earner :%s (ID: %d) - Salary: %.2f
\n",employees[p].name,employees[p].empID,employees[p].salary);
return 0;
Problem 9: Century Leap Year Validator with Exception Handling
Problem Statement: Write a program to determine whether a given year is a leap year or a
century year. If it is a
century year (divisible by 100), ensure it’s valid according to the Gregorian calendar (i.e., year ≥
1582). Return error
messages for years earlier than 1582.
Function Prototype:
int isValidLeapYear(int year);
Requirements:
• A year is a leap year if:
– Divisible by 4;
– Not divisible by 100, unless divisible by 400.
• Return -1 for invalid (pre-Gregorian) years.
#include<stdio.h>
int isValidLeapYear(int year)
if (year < 1582) {
return -1;
// invalid year (before Gregorian calendar)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 1;
Else
return 0;
int main()
{
int year, result;
printf("Enter a year: ");
scanf("%d", &year);
result = isValidLeapYear(year);
if (result == -1)
printf("Error: Year must be 1582 or later (Gregorian calendar).\n");
else if (result == 1)
printf("%d is a leap year.\n", year);
Else
printf("%d is not a leap year.\n", year);
return 0;
}
Problem 10: Generalized Fibonacci with Dynamic Base Terms
Problem Statement: Write a program to generate a Fibonacci-like series with custom first two
terms (user input), up
to n terms.
Function Prototype:
void generateGeneralFibonacci(int a, int b, int n);
#include<stdio.h>
void generateGeneralFibonacci(int a,int b,int n)
int i,t;
for(i=1;i<=n;i++)
t=a;
printf("%d ",a);
a=b;
b=t+b;
}
int main()
int a,b,n;
printf("Enter the 1st two terms:");
scanf("%d %d",&a,&b);
printf("Enter the number of terms to be printed:");
scanf("%d",&n);
generateGeneralFibonacci(a,b,n);
return 0;
Problem 11: Symmetric Numeric Pyramid with Center Alignment
Problem Statement: Print a center-aligned symmetric numeric pyramid. Each level should mirror
the numbers.
Expected Output (for n = 4):
121
12321
1234321
Function Prototype:
void printSymmetricPyramid(int n);
#include <stdio.h>
void printSymmetricPyramid(int n)
//maximum width is length of the last row
int width = (2 * n - 1) + (n - 1); // The last row has 2*n-1 numbers, plus (n-1) spaces
for (int i = 1; i <= n; i++)
{
// Print starting spaces
int spaces = width - (2 * i - 1); //space needed to center align the pyramid row
for (int j = 1; j <= spaces / 2; j++)
printf(" ");
for (int j = 1; j <= i; j++)
printf("%d", j); // print number without trailing space
if (j < i) //adding space between numbers, but not after the last one printf(" ");
for (int j = i - 1; j >= 1; j--)
printf(" %d", j);
}
printf("\n");
int main()
int n;
printf("Enter the number of levels: "); scanf("%d", &n);
printSymmetricPyramid(n);
return 0;
Problem 12: Matrix Multiplication with Dimension Checks
Problem Statement: Multiply two matrices only if their dimensions are compatible. Implement a
check for multipli-
cation validity and prompt re-entry on error.
Function Prototype:
void multiplyMatrices(int A[][10], int B[][10], int result[][10], int m1, int n1, int m2, int n2);
Requirements:
• Matrix A dimensions: m1 × n1
• Matrix B dimensions: m2 × n2
• Valid only if n1 = m2
#include <stdio.h>
void multiplyMatrices(int A[][10], int B[][10], int result[][10], int m1, int n1, int m2, int n2)
if (n1 != m2)
return;
}
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
result[i][j] = 0;
for (int k = 0; k < n1; k++)
result[i][j] += A[i][k] * B[k][j];
int main()
int m1, n1, m2, n2;
printf("enter the dimensions of Matrix A (rows and columns): "); scanf("%d %d", &m1, &n1);
printf("enter the dimensions of Matrix B (rows and columns): "); scanf("%d %d", &m2, &n2);
while (n1 != m2)
printf("error!: Matrix dimensions are not compatible for multiplication.\n"); printf("Re-enter the
dimensions of Matrix B (rows and columns): "); scanf("%d %d", &m2, &n2);
int A[10][10], B[10][10], result[10][10];
printf("enter elements of Matrix A (%dx%d):\n", m1, n1); for (int i = 0; i < m1; i++)
for (int j = 0; j < n1; j++)
scanf("%d", &A[i][j]);
}
printf("enter elements of Matrix B (%dx%d):\n", m2, n2); for (int i = 0; i < m2; i++)
for (int j = 0; j < n2; j++)
scanf("%d", &B[i][j]);
multiplyMatrices(A, B, result, m1, n1, m2, n2);
printf("\nResultant Matrix (%dx%d):\n", m1, n2);
for (int i = 0; i < m1; i++);
for (int j = 0; j < n2; j++)
printf("%d ", result[i][j]);
printf("\n");
}
return 0;
Problem 13: Advanced Palindrome Checker (Ignoring Non-Alphanumerics)
Problem Statement: Check if a given string is a palindrome, ignoring punctuation, spaces, and
case.
Function Prototype:
int isAdvancedPalindrome(char str[]);
Sample Input/Output:
Enter a string: A man, a plan, a canal: Panama
The string is a palindrome.
Requirements:
• Ignore spaces, punctuation, and case sensitivity.
• Use only character array manipulation.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isAdvancedPalindrome(char str[])
int length = strlen(str); char newstr[length + 1]; int i, newIndex = 0;
for(i = 0; i < length; i++)
if(isalnum(str[i]))
newstr[newIndex++] = tolower(str[i]); //to convert to lowercase
newstr[newIndex] = '\0'; //for terminating the string int start = 0, end = newIndex - 1;
while(end >= start)
if (newstr[start] != newstr[end])
{
return 0;
start++; end--;
return 1;
int main()
char str[100]; printf("enter a string: "); scanf("%[^\n]", str);
if(isAdvancedPalindrome(str))
printf(“the string is palindrome \n”);
else
{
printf(“the string is not a palindrome \n”);
Problem 14: File Encryption and Decryption (Caesar Cipher)
Problem Statement: Write a program that takes user input, encrypts it using Caesar cipher (shift
by 3), writes it to
a file, and then decrypts and displays it.
Function Prototypes:
void encryptAndWriteToFile(char filename[], char text[]);
void readAndDecryptFromFile(char filename[]);
#include <stdio.h> #include <ctype.h>
void encryptAndWriteToFile(char filename[], char text[])
{
FILE *file = fopen(filename, "w"); if (file == NULL)
printf("Error opening file for writing.\n"); return;
int i = 0;
while (text[i] != '\0')
if (isalpha(text[i]))
if (isupper(text[i]))
text[i] = 'A' + (text[i] - 'A' + 3) % 26; //this is the caesar cipher
else
{
text[i] = 'a' + (text[i] - 'a' + 3) % 26;
fputc(text[i], file); i++;
fclose(file);
printf("Encrypted text written to file.\n");
void readAndDecryptFromFile(char filename[])
FILE *file = fopen(filename, "r"); if (file == NULL)
printf("Error opening file for reading.\n"); return;
}
printf("Reading from file:\n"); char ch;
while ((ch = fgetc(file)) != EOF)
if (isalpha(ch))
if (isupper(ch))
ch = 'A' + (ch - 'A' - 3 + 26) % 26;
else
ch = 'a' + (ch - 'a' - 3 + 26) % 26;
printf("%c", ch);
printf("\n");
fclose(file);
int main()
char filename[] = "encrypted.txt";
char text[100];
printf("Enter a sentence: "); scanf("%[^\n]", text);
encryptAndWriteToFile(filename, text); readAndDecryptFromFile(filename);
return 0;
Problem 15: Count Words, Lines, and Characters in a File
Problem Statement: Write a program that reads a text file and counts the total number of:
• Characters
• Words
• Lines
Function Prototype:
void countFileStats(char filename[]);
#include <stdio.h> #include <ctype.h>
void countFileStats(char filename[])
FILE *file = fopen(filename, "r"); if (file == NULL)
printf("Error opening file.\n"); return;
int chars = 0, words = 0, lines = 0, inWord = 0; char ch;
while ((ch = fgetc(file)) != EOF)
chars++;
if(ch == '\n')
lines++;
if (isspace(ch))
if(inWord)
words++; inWord = 0;
}
else
inWord = 1;
//to count if the file doesn't end with a whitespace if(inWord)
words++;
//if file doesn't end with a newline, count the last line if (chars > 0 && ch == EOF && inWord)
lines++;
fclose(file);
printf("File statistics for \"%s\":\n", filename); printf("Characters: %d\n", chars); printf("Words: %d
\n", words);
printf("Lines: %d\n", lines);
int main()
char filename[100]; printf("Enter the filename: "); scanf("%99s", filename);
countFileStats(filename);
return 0;
Problem 16: Sort Lines in a File Alphabetically
Problem Statement: Write a program that reads all lines from a text file, sorts them in ascending
(alphabetical) order,
and writes the sorted lines to a new file.
Function Prototype:
void sortLinesInFile(char inputFile[], char outputFile[]);
#include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX_LINES 1000
#define MAX_LENGTH 100
void sortLinesInFile(char inputFile[], char outputFile[])
char lines[MAX_LINES][MAX_LENGTH]; int count = 0;
FILE *input = fopen(inputFile, "r"); FILE *output;
char ch;
int pos = 0;
if (input == NULL)
{
printf("Error opening input file.\n"); exit(1);
while (count < MAX_LINES && (ch = fgetc(input)) != EOF)
if (ch == '\n' || pos == MAX_LENGTH - 1)
lines[count][pos] = '\0'; count++;
pos = 0;
else
lines[count][pos++] = ch;
fclose(input);
for (int i = 0; i < count - 1; i++)
for (int j = i + 1; j < count; j++)
if (strcmp(lines[i], lines[j]) > 0)
char temp[MAX_LENGTH]; strcpy(temp, lines[i]); strcpy(lines[i], lines[j]); strcpy(lines[j], temp);
output = fopen(outputFile, "w"); if (output == NULL)
printf("Error opening output file.\n"); exit(1);
for (int i = 0; i < count; i++)
{
fprintf(output, "%s\n", lines[i]);
fclose(output);
int main()
sortLinesInFile("input.txt", "sorted.txt");
printf("Original lines in input.txt:\n"); FILE *input = fopen("input.txt", "r"); char ch;
while ((ch = fgetc(input)) != EOF)
putchar(ch);
fclose(input);
printf("\nSorted lines written to sorted.txt:\n"); FILE *output = fopen("sorted.txt", "r");
while ((ch = fgetc(output)) != EOF)
putchar(ch);
fclose(output);
return 0;
Problem 17: Store and Retrieve Student Records Using File
Problem Statement: Design a structure to store student details (Roll Number, Name, Marks).
Write a program to:
• Write n student records to a binary file.
• Read the data back and display students with marks ¿ 80.
Structure Definition:
struct Student {
int roll;
char name[50];
float marks;
};
Function Prototype:
void saveStudentsToFile(char filename[], struct Student students[], int n);
void displayTopStudents(char filename[]);
#include <stdio.h> #include <stdlib.h> #define MAX 100
struct Student
int roll;
char name[50]; float marks;
};
void saveStudentsToFile(char filename[], struct Student students[], int n)
{
FILE *file = fopen(filename, "wb"); //to open the file in binary write mode if (file == NULL)
printf("Error opening file for writing.\n"); exit(1);
fwrite(students, sizeof(struct Student), n, file); fclose(file);
void displayTopStudents(char filename[])
FILE *file = fopen(filename, "rb"); //to open the file in binary read mode if (file == NULL)
printf("Error opening file for reading.\n"); exit(1);
printf("students scoring above 80:\n");
struct Student s;
while (fread(&s, sizeof(struct Student), 1, file) == 1)
if (s.marks > 80.0)
printf("Roll: %d, Name: %s, Marks: %.1f\n", s.roll, s.name, s.marks);
fclose(file);
int main()
int num, i;
struct Student students[MAX]; printf("enter the number of students:"); scanf("%d", &num);
for(i = 0; i < num; i++)
printf("\n===enter details for student %d: ===\n", i + 1); printf("roll no: ");
scanf("%d",&students[i].roll); printf("name: ");
scanf("%s", students[i].name); printf("marks: ");
scanf("%f", &students[i].marks);
saveStudentsToFile("students.dat", students, 3); displayTopStudents("students.dat");
return 0;