0% found this document useful (0 votes)
21 views55 pages

PPS Lab All Programs

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)
21 views55 pages

PPS Lab All Programs

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/ 55

BCS151 / BCS251: PROGRAMMING FOR PROBLEM SOLVINGLAB

1. WAP that accepts the marks of 5 subjects and finds the sum and percentage marks
obtained by the student.
2. WAP that calculates the Simple Interest and Compound Interest. The Principal, Amount,
Rate of Interest and Time are entered through the keyboard.
3. WAP to calculate the area and circumference of a circle.
4. WAP that accepts the temperature in Centigrade and converts into Fahrenheit using
the formula C/5=(F-32)/9.
5. WAP that swaps values of two variables using a third variable.
6. WAP that checks whether the two numbers entered by the user are equal or not.
7. WAP to find the greatest of three numbers.
8. WAP that finds whether a given number is even or odd.
9. WAP that tells whether a given year is a leap year or not.
10. WAP that accepts marks of five subjects and finds percentage and prints grades according
to the following criteria:
Between 90-100%-----Print ‘A’
80-90%-----------------Print ‘B’
60-80%-----------------Print ‘C’
Below 60%-------------Print ‘D’
11. WAP that takes two operands and one operator from the user, perform the operation,
and prints the result by using Switch statement.
12. WAP to print the sum of all numbers up to a given number.
13. WAP to find the factorial of a given number.
14. WAP to print sum of even and odd numbers from 1 to N numbers.
15. WAP to print the Fibonacci series.
16. WAP to check whether the entered number is prime or not.
17. WAP to find the sum of digits of the entered number.
18. WAP to find the reverse of a number.
19. WAP to print Armstrong numbers from 1 to 100.
20. WAP to convert binary number into decimal number and vice versa.
21. WAP that simply takes elements of the array from the user and finds the sum of these
elements.
22. WAP that inputs two arrays and saves sum of corresponding elements of these arrays in
a third array and prints them.
23. WAP to find the minimum and maximum element of the array.
24. WAP to search an element in a array using Linear Search.
25. WAP to sort the elements of the array in ascending order using Bubble Sort technique.
26. WAP to add and multiply two matrices of order nxn.
27. WAP that finds the sum of diagonal elements of a mxn matrix.
28. WAP to implement strlen (), strcat (),strcpy () using the concept of Functions.
29. Define a structure data type TRAIN_INFO. The type contain Train No.: integer type
Train name: string Departure Time: aggregate type TIME Arrival Time: aggregate type
TIME Start station: string End station: string The structure type Time contains two integer
members: hour and minute. Maintain a train timetable and implement the following
operations:
a. List all the trains (sorted according to train number) that depart from a particular
section.
b. List all the trains that depart from a particular station at a particular time.
c. List all he trains that depart from a particular station within the next one hour of
a given time.
d. List all the trains between a pair of start station and end station.
30. WAP to swap two elements using the concept of pointers.
31. WAP to compare the contents of two files and determine whether they are same or not.
32. WAP to check whether a given word exists in a file or not. If yes then find the number
of times it occurs.
1. WAP that accepts the marks of 5 subjects and finds the sum and percentage
marks obtained by the student.
a. Without Array

#include <stdio.h>
int main() {
int marks1, marks2, marks3, marks4, marks5;
int sum;
float percentage;
// Accept marks for 5 subjects
printf("Enter marks for 5 subjects:\n");
scanf("%d %d %d %d %d", &marks1, &marks2, &marks3, &marks4, &marks5);
// Calculate sum of marks obtained
sum = marks1 + marks2 + marks3 + marks4 + marks5;
// Calculate percentage of marks
obtained percentage = (float)sum / 5.0;
// Display sum and percentage of marks obtained
printf("\nSum of marks: %d\n", sum);
printf("Percentage of marks obtained: %.2f%%\n",
percentage); return 0;
}
Sample output:
Enter marks for 5 subjects:
75 80 85 90 95
Sum of marks: 425
Percentage of marks obtained: 85.00%
b. Using Array
#include
<stdio.h> int
main() {
int marks[5];
int sum = 0;
float percentage;
// Accept marks for 5 subjects
printf("Enter marks for 5 subjects:\n"); for
(int i = 0; i < 5; i++) {
printf("Subject %d: ", i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
// Calculate percentage of marks obtained
percentage = (float)sum / 5.0;
// Display sum and percentage of marks obtained
printf("\nSum of marks: %d\n", sum);
printf("Percentage of marks obtained: %.2f%%\n",
percentage); return 0;
}

Sample output:
Enter marks for 5 subjects:
S1: 75
u
b
j
e
c
t
S2: 80
u
b
j
e
c
t
S3: 85
u
b
j
e
c
t
S4: 90
u
b
j
e
c
t
S5: 95
u
b
j
e
c
t

Sum of marks: 425


Percentage of marks obtained: 85.00%
2. WAP that calculates the Simple Interest and Compound Interest. The
Principal, Amount, Rate of Interest and Time are entered through the
keyboard.

#include <stdio.h>
#include
<math.h> int
main() {
float principal, rate, time, si, ci; int n;
// Accept input for principal, rate of interest, time, and number of times
compounded
printf("Enter the principal amount: ");
scanf("%f", &principal);
printf("Enter the rate of interest: ");
scanf("%f", &rate);
printf("Enter the time period: ");
scanf("%f", &time);
printf("Enter the number of times the interest is compounded in a year: ");
scanf("%d", &n);
// Calculate Simple Interest
si = (principal * rate * time) / 100.0; printf("\
nSimple Interest = %.2f\n", si);
// Calculate Compound Interest
ci = principal * pow(1 + (rate / (100.0 * n)), n * time);
printf("Compound Interest = %.2f\n", ci);
return 0;
}
Sample output:
Enter the principal amount: 10000
Enter the rate of interest: 10.5
Enter the time period: 2
Enter the number of times the interest is compounded in a year:
4 Simple Interest = 2100.00
Compound Interest = 11203.54
3. WAP to calculate the area and circumference of a circle.

#include
<stdio.h>
#define PI
3.14159 int
main() {
float radius, area, circumference;
// Accept input for radius
printf("Enter the radius of the circle: "); scanf("%f",
&radius);
// Calculate area and circumference
area = PI * radius * radius;
circumference = 2 * PI * radius;
// Display area and circumference printf("\
nArea of the circle = %.2f\n", area);
printf("Circumference of the circle = %.2f\n", circumference);
return 0;
}
Sample output:
Enter the radius of the circle: 5.5
Area of the circle = 95.03
Circumference of the circle =
34.56
4. WAP that accepts the temperature in Centigrade and converts into Fahrenheit
using the formula C/5=(F-32)/9
#include <stdio.h>
int main() {
float celsius, fahrenheit;
// Accept input for temperature in Celsius
printf("Enter the temperature in Celsius: ");
scanf("%f", &celsius);
// Calculate temperature in Fahrenheit
fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
// Display temperature in Fahrenheit
printf("\nTemperature in Fahrenheit = %.2f\n", fahrenheit);
return 0;
}
Sample output:
Enter the temperature in Celsius: 25
Temperature in Fahrenheit = 77.00
5. WAP that swaps values of two variables
1. using a third variable
#include <stdio.h>
int main() {
int num1, num2, temp;
// Accept input for num1 and num2
printf("Enter the value of num1: ");
scanf("%d", &num1);
printf("Enter the value of num2: ");
scanf("%d", &num2);
// Swap values using a third variable
temp = num1;
num1 =
num2;
num2 =
temp;
// Display swapped values
printf("\nAfter swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
return 0;
}
Sample output:
Enter the value of num1: 5
Enter the value of num2: 10
After swapping:
num1 = 10
num2 = 5
2. Without using a third variable

#include
<stdio.h> int
main() {
int a, b;
printf("Enter value of a: ");
scanf("%d", &a);
printf("Enter value of b: ");
scanf("%d", &b);
printf("Before swapping, a = %d and b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping, a = %d and b = %d\n", a, b);
return 0;
}
Sample output:

Enter the value of a: 5


Enter the value of b: 10
After swapping:
a = 10
b=5
6. WAP that checks whether the two numbers entered by the user are equal or not.

#include
<stdio.h> int
main() {
int num1, num2;
// Accept input for num1 and
num2 printf("Enter the first
number: "); scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Check if num1 and num2 are
equal if (num1 == num2) {
printf("\nThe two numbers are equal.\n");
}
else {
printf("\nThe two numbers are not equal.\n");
}
return 0;
}
Sample output:
Enter the first number: 5
Enter the second number: 5
The two numbers are equal.
7. WAP to find the greatest of three numbers.

#include
<stdio.h> int
main() {
int num1, num2, num3, greatest;
// Accept input for num1, num2, and num3
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Enter the third number: ");
scanf("%d", &num3);
// Find the greatest number
greatest = num1;
if (num2 > greatest)
{ greatest = num2;
}
if (num3 > greatest)
{ greatest = num3;
}
// Display the greatest number
printf("\nThe greatest number is: %d\n", greatest);
return 0;
}
Sample output:
Enter the first number: 10
Enter the second number:
20 Enter the third number:
30 The greatest number is:
30
8. WAP that finds whether a given number is even or odd.

#include
<stdio.h> int
main() {
int num;
// Accept input for num
printf("Enter a number: ");
scanf("%d", &num);
// Check if num is even or odd
if (num % 2 == 0) {
printf("\nThe number is even.\n");
}
else {
printf("\nThe number is odd.\n");
}
return 0;
}
Sample output:
Enter a number: 5
The number is
odd.
9. WAP that tells whether a given year is a leap year or not.

#include
<stdio.h> int
main() {
int year;
// Accept input for year
printf("Enter a year: ");
scanf("%d", &year);
// Check if year is a leap year if
(year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
printf("\nThe year is a leap year.\n");
}
else {
printf("\nThe year is not a leap year.\n");
}
}
else {
printf("\nThe year is a leap year.\n");
}
}
else {
printf("\nThe year is not a leap year.\n");
}

return 0;
}

Sample output:
Enter a year: 2024
The year is a leap year.
10. WAP that accepts marks of five subjects and finds percentage and prints
grades according to the following criteria:
Between 90-100%-----Print ‘A’
80-90%-----------------Print ‘B’
60-80%-----------------Print ‘C’
Below 60%-------------Print ‘D
a. using an
array: #include
<stdio.h> int main()
{
int marks[5], total = 0, i;
float percentage;
// Accept input for marks of five subjects
for (i = 0; i < 5; i++) {
printf("Enter marks for subject %d: ", i+1);
scanf("%d", &marks[i]);
total += marks[i];
}
// Calculate percentage
percentage = (float)total / 5;
// Print percentage and grade printf("\
nPercentage: %.2f%%\n", percentage); if
(percentage >= 90 && percentage <= 100)
{
printf("Grade: A\n");
}
else if (percentage >= 80 && percentage < 90)
{ printf("Grade: B\n");
}
else if (percentage >= 60 && percentage < 80)
{ printf("Grade: C\n");
}
else {
printf("Grade: D\n");
}
return 0;
}
Sample output:

Enter marks for subject 1: 80


Enter marks for subject 2: 85
Enter marks for subject 3: 90
Enter marks for subject 4: 75
Enter marks for subject 5: 70

Percentage: 80.00%
Grade: B

b. without using an

array: #include <stdio.h>


int main() {
int marks1, marks2, marks3, marks4, marks5, total;
float percentage;

// Accept input for marks of five subjects


printf("Enter marks for subject 1: ");
scanf("%d", &marks1);
printf("Enter marks for subject 2: ");
scanf("%d", &marks2);
printf("Enter marks for subject 3: ");
scanf("%d", &marks3);
printf("Enter marks for subject 4: ");
scanf("%d", &marks4);
printf("Enter marks for subject 5: ");
scanf("%d", &marks5);

// Calculate total marks and percentage


total = marks1 + marks2 + marks3 + marks4 +
marks5; percentage = (float)total / 5;

// Print percentage and grade printf("\


nPercentage: %.2f%%\n", percentage); if
(percentage >= 90 && percentage <= 100)
{
printf("Grade: A\n");
}
else if (percentage >= 80 && percentage < 90)
{ printf("Grade: B\n");
}
else if (percentage >= 60 && percentage < 80)
{ printf("Grade: C\n");
}
else {
printf("Grade: D\n");
}

return 0;
}
Sample output:

Enter marks for subject 1: 80


Enter marks for subject 2: 85
Enter marks for subject 3: 90
Enter marks for subject 4: 75
Enter marks for subject 5: 70

Percentage: 80.00%
Grade: B
11. WAP that takes two operands and one operator from the user, perform the
operation, and prints the result by using Switch statement.
#include <stdio.h>
int main() {
float operand1, operand2, result;
char operator;
// Accept input for operands and operator
printf("Enter first operand: "); scanf("%f",
&operand1);
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator); // note the space before %c to consume any
preceding newline character
printf("Enter second operand: ");
scanf("%f", &operand2);
// Perform operation based on operator
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
printf("Invalid operator\n");
return 1; // exit program with error status
}
printf("Result: %.2f\n", result);
return 0;
}
Sample output:
Enter first operand: 5.4
Enter operator (+, -, *, /): *
Enter second operand: 3.2
Result: 17.28
12. WAP to print the sum of all numbers up to a given number

#include
<stdio.h> int
main() {
int n, i, sum = 0;
// Accept input for n
printf("Enter a number: ");
scanf("%d", &n);
// Calculate sum of all numbers up to n
for (i = 1; i <= n; i++) {
sum += i;
}
// Print result
printf("Sum of all numbers up to %d is %d\n", n, sum);

return 0;
}
Sample output:
Enter a number: 10
Sum of all numbers up to 10 is 55
13. WAP to find the factorial of a given number.

#include
<stdio.h> int
main() {
int n, i, fact = 1;
// Accept input for n
printf("Enter a number: ");
scanf("%d", &n);
// Calculate factorial of n
for (i = 1; i <= n; i++) {
fact *= i;
}
// Print result
printf("Factorial of %d is %d\n", n, fact); return
0;
}
Sample output:
Enter a number: 5
Factorial of 5 is 120
14. WAP to print sum of even and odd numbers from 1 to N numbers

#include
<stdio.h> int
main() {
int n, i, sum_even = 0, sum_odd = 0;
// Accept input for n
printf("Enter a number: ");
scanf("%d", &n);
// Calculate sum of even and odd numbers up
to n for (i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum_even += i;
} else {
sum_odd += i;
}
}
// Print result
printf("Sum of even numbers up to %d is %d\n", n, sum_even);
printf("Sum of odd numbers up to %d is %d\n", n, sum_odd);

return 0;
}
Sample output:
Enter a number: 10
Sum of even numbers up to 10 is
30 Sum of odd numbers up to 10 is
25
15. WAP to print the Fibonacci series.

#include
<stdio.h> int
main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
// Accept input for n
printf("Enter the number of terms: ");
scanf("%d", &n);

// Print first two terms


printf("Fibonacci Series: %d, %d, ", t1, t2);

// Generate and print the remaining terms


for (i = 3; i <= n; i++) {
nextTerm = t1 + t2;
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
}

return 0;
}
Sample output:
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
16. WAP to check whether the entered number is prime or not.

#include

<stdio.h> int

main() {
int n, i, isPrime = 1;

// Accept input for n


printf("Enter a number: ");
scanf("%d", &n);

// Check for prime number


for (i = 2; i <= n / 2; i++) { if
(n % i == 0) {
isPrime = 0;
break;
}
}

// Print result if
(n == 1) {
printf("%d is neither prime nor composite.\n", n);
} else if (isPrime) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}

return 0;
}
Sample output:
Enter a number:
17
17 is a prime number.
17. WAP to find the sum of digits of the entered number.

#include
<stdio.h> int
main() {
int n, digit, sum = 0;
// Accept input for n
printf("Enter a number: ");
scanf("%d", &n);

// Find the sum of digits


while (n > 0) {
digit = n %
10; sum +=
digit; n /= 10;
}

// Print result
printf("The sum of digits is %d.\n", sum);

return 0;
}
Sample output:
Enter a number: 12345
The sum of digits is 15.
18. WAP to find the reverse of a number.

#include

<stdio.h> int

main() {
int n, digit, reverse = 0;

// Accept input for n


printf("Enter a number: ");
scanf("%d", &n);

// Reverse the number


while (n > 0) {
digit = n % 10;
reverse = reverse * 10 + digit;
n /= 10;
}

// Print result
printf("The reverse of the number is %d.\n", reverse);

return 0;
}
Sample output:

Enter a number: 12345


The reverse of the number is 54321.
19. WAP to print Armstrong numbers from 1 to 1000.

#include <stdio.h>
#include <math.h>

int main() {
int n, originalNumber, digit, sum;

// Loop through numbers from 1 to


1000 for (n = 1; n <= 1000; n++) {
originalNumber = n;
sum = 0;

// Find the sum of cubes of digits


while (originalNumber > 0) {
digit = originalNumber % 10;
sum += pow(digit, 3);
originalNumber /= 10;
}

// Check if the number is Armstrong


if (n == sum) {
printf("%d ", n);
}
}

return 0;
}

Sample output:
Copy code
1 153 370 371 407
20. WAP to convert binary number into decimal number and vice versa
#include <stdio.h>
#include <math.h>
// Function to convert binary to decimal
int binaryToDecimal(int binary) {
int decimal = 0, power = 0;
while (binary > 0) {
int digit = binary % 10;
decimal += digit * pow(2, power);
binary /= 10;
power++;
}
return decimal;
}
// Function to convert decimal to binary
int decimalToBinary(int decimal) {
int binary = 0, digit, power = 0;
while (decimal > 0) {
digit = decimal % 2;
binary += digit * pow(10, power);
decimal /= 2;
power++;
}
return binary;
}
int main() {
int choice, number;
printf("Enter your choice:\n1. Binary to Decimal\n2. Decimal to Binary\n");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter binary number: ");
scanf("%d", &number);
printf("Decimal equivalent is: %d", binaryToDecimal(number));
}
else if (choice == 2) {
printf("Enter decimal number: ");
scanf("%d", &number);
printf("Binary equivalent is: %d", decimalToBinary(number));
}
else {
printf("Invalid choice!");
}

return 0;
}
Sample output:

Enter your choice:


1. Binary to Decimal
2. Decimal to
Binary 1
Enter binary number:
101010 Decimal equivalent
is: 42

Enter your choice:


1. Binary to Decimal
2. Decimal to
Binary 2
Enter decimal number: 42
Binary equivalent is:
101010
21. WAP that simply takes elements of the array from the user and finds the sum of
these Elements.
#include <stdio.h>
int main() {
int arr[100], n, i, sum = 0;

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


scanf("%d", &n);

printf("Enter %d elements:\n", n);

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


{ scanf("%d", &arr[i]);
sum += arr[i];
}

printf("The sum of the elements is %d\n", sum);

return 0;
}
Sample Output:
Enter the number of elements:
5 Enter 5 elements:
12345
The sum of the elements is 15
22. WAP in C that inputs two arrays and saves sum of corresponding elements of
these arrays in a third array and prints them.

#include
<stdio.h> int
main() {
int n;
printf("Enter the number of elements in the arrays: ");
scanf("%d", &n);

int arr1[n], arr2[n], sum[n];


printf("Enter the elements of the first array: ");
for(int i=0; i<n; i++) {
scanf("%d", &arr1[i]);
}
printf("Enter the elements of the second array: ");
for(int i=0; i<n; i++) {
scanf("%d", &arr2[i]);
}
printf("Sum of corresponding elements of the two arrays: ");
for(int i=0; i<n; i++) {
sum[i] = arr1[i] + arr2[i];
printf("%d ", sum[i]);
}
return 0;
}
Sample Output:
Enter the size of the arrays: 5
Enter the elements of the first array:
4
7
2
9
1
Enter the elements of the second
array: 5
8
3
6
2
The sum of the corresponding elements is:
9
15
5
15
3
23. WAP to find the minimum and maximum element of the array
#include
<stdio.h> int
main() {
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min = arr[0], max = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] < min)
{ min = arr[i];
}
if (arr[i] > max)
{ max = arr[i];
}
}
printf("Minimum element in the array: %d\n",
min); printf("Maximum element in the array: %d\
n", max); return 0;
}
Sample Output:
Enter the number of elements in the array: 6
Enter the elements of the array:
263815
Minimum element in the array:
1 Maximum element in the
array: 8
24. WAP to search an element in a array using Linear Search.
#include <stdio.h>
#define MAX_SIZE
100 int main()
{
int arr[MAX_SIZE];
int n, i, search_element;
int found = 0;
// Input size and elements of array
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter elements of the array:\n"); for(i=0;
i<n; i++)
{
scanf("%d", &arr[i]);
}
// Input element to search
printf("Enter the element to search: ");
scanf("%d", &search_element);
// Linear Search Algorithm
for(i=0; i<n; i++)
{
if(arr[i] == search_element)
{
found =
1; break;
}
}
// Display the result
if(found == 1)
{
printf("Element %d is found at position %d.", search_element, i+1);
}
else
{
printf("Element %d is not found in the array.", search_element);
}

return 0;
}
Sample Output:
Enter the size of the array: 5
Enter elements of the array:
12 6 8 20 11
Enter the element to search: 20
Element 20 is found at position 4.
25. WAP to sort the elements of the array in ascending order using Bubble Sort technique.
#include
<stdio.h> int
main() {
int arr[100], n, i, j, temp;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

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


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

// Bubble Sort algorithm


for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// swap the adjacent elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

printf("Sorted array in ascending order: ");


for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Sample Output:
Enter the number of elements in the array: 5
Enter the elements of the array:
23 12 45 8 17
Sorted array in ascending order: 8 12 17 23 45
26. WAP to add and multiply two matrices of order nxn.
#include
<stdio.h> int
main() {
int n;
printf("Enter the order of matrices: ");
scanf("%d", &n);

int A[n][n], B[n][n], C[n][n], D[n][n]; int


i, j, k;

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


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

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


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

// Multiplication of matrices A and B printf("\


nMultiplication of matrices A and B:\n"); for(i=0;
i<n; i++) {
for(j=0; j<n; j++)
{ D[i][j] = 0;
for(k=0; k<n; k++) {
D[i][j] += A[i][k] * B[k][j];
}
printf("%d ", D[i][j]);
}
printf("\n");
}

return 0;
}
Output:
Enter the order of matrices: 2
Enter the elements of matrix
A: 1 2
34
Enter the elements of matrix
B: 5 6
78

Multiplication of matrices A and B:


19 22
43 50
27. WAP that finds the sum of diagonal elements of a mxn matrix
#include
<stdio.h> int
main()
{
int matrix[10][10], i, j, rows, columns, sum = 0; printf("Enter
the number of rows and columns of the matrix: "); scanf("%d
%d", &rows, &columns);
printf("Enter the elements of the matrix:\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf("\nThe matrix is:\n");

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


{
for(j = 0; j < columns; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
if(rows == columns)
{
for(i = 0; i < rows; i++)
{
sum = sum + matrix[i][i];
}
printf("\nThe sum of diagonal elements is: %d", sum);
}
else
{
printf("\nDiagonal sum is not possible for the given matrix.");
}

return 0;
}
Sample Output:
Enter the number of rows and columns of the matrix: 3
3 Enter the elements of the matrix:
123
456
789

The matrix is:


123
456
789

The sum of diagonal elements is: 15


28. WAP to implement strlen (), strcat (),strcpy () using the concept of Functions.
#include <stdio.h>
// Function to find length of a string int
strlen(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
// Function to copy one string to another
void strcpy(char dest[], char src[]) {
int i = 0;
while (src[i] != '\0')
{ dest[i] = src[i]; i+
+;
}
dest[i] = '\0';
}
// Function to concatenate two strings
void strcat(char dest[], char src[]) {
int dest_len = strlen(dest); int
i = 0;
while (src[i] != '\0')
{ dest[dest_len + i] = src[i];
i++;
}
dest[dest_len + i] = '\0';
}
int main() {
// Test strlen()
char str1[] = "Hello"; int
len = strlen(str1);
printf("Length of '%s' is %d\n", str1, len);

// Test strcpy() char


str2[10];
strcpy(str2, str1);
printf("Copied string: '%s'\n", str2);
// Test strcat()
char str3[20] = "Good
"; char str4[] =
"morning"; strcat(str3,
str4);
printf("Concatenated string: '%s'\n", str3);

return 0;
}
Output:
Length of 'Hello' is 5
Copied string: 'Hello'
Concatenated string: 'Good morning'
29. Define a structure data type TRAIN_INFO. The type contain Train No.: integer type
Train name: string Departure Time: aggregate type TIME Arrival Time: aggregate
type TIME Start station: string End station: string The structure type Time contains
two integer members: hour and minute. Maintain a train timetable and implement the
following operations:
a. List all the trains (sorted according to train number) that depart from a
particular section.
b. List all the trains that depart from a particular station at a particular time.
c. List all he trains that depart from a particular station within the next one hour
of a given time.
d. List all the trains between a pair of start station and end station.

#include<stdio.h>
#include<string.h>
#define MAX 50
typedef struct
TIME{
int hour; int
minute;
}TIME;
typedef struct
TRAIN_INFO{ int
train_no;
char
train_name[35];
char start_st[35];
char end_st[35];
TIME dept_time;
TIME arr_time;
} TRAIN;
void train_edit (TRAIN *, int *); int
main (void)
{
int no_of_trains = 0;
int i;
int choice;
char dept_st[35];
char arr_st[35];
TIME train_time;
TRAIN train[MAX];
//Call train_edit function first time.
train_edit (train, &no_of_trains);
while (1)
{
//Display Main Menu
printf ("\t\t\t****MENU****\n");
printf ("1. List all the trains departed from a particular station.\n");
printf ("2. List all the trains departed from a particular station at a particular time.\
n");
printf ("3. List all the trains departed from particular station within the next one hour
of a given time.\n");
printf ("4. List all the trains between a pair of start station and end
station.\n");
printf ("5. Edit train details.\n"); printf
("6. Exit.\n");
printf ("Your choice: ");

//Input choice
scanf ("%d", &choice);
switch (choice)
{
//List all the trains departed from a particular station.
case 1:
printf ("\n\t\t****INPUT DETAILS****\n");
printf ("Depart Station: ");
fflush (stdin);
gets (dept_st);
//Print trains
for (i = 0; i <= no_of_trains - 1; i++)
{
if (strcmp (train[i].start_st, dept_st) == 0)
{
printf ("%d\t\t%s\t%s\t%s\t%d:%d\t%d:%d\n", train[i].train_no,
train[i].train_name,
train[i].start_st, train[i].end_st, train[i].dept_time.hour,
train[i].dept_time.minute, train[i].arr_time.hour,
train[i].arr_time.minute);
}
}
printf ("\n");
break;
//List all the trains departed from a particular station at a particular time. case
2:
printf ("\n\t\t****INPUT DETAILS****\n");
printf ("Depart Station: ");
fflush (stdin);
gets (dept_st);
printf ("Train Time: \n");
printf ("Hour: ");
scanf ("%d", &train_time.hour);
printf ("Minute: ");
scanf ("%d", &train_time.minute);
//Print trains
for (i = 0; i <= no_of_trains - 1; i++)
{
if (strcmp (train[i].start_st, dept_st) == 0 && train[i].dept_time.hour
==
train_time.hour
&& train[i].dept_time.minute == train_time.minute)
{
printf ("%d\t\t%s\t%s\t%s\t%d:%d\t%d:%d\n", train[i].train_no,
train[i].train_name, train[i].start_st, train[i].end_st,
train[i].dept_time.hour,
train[i].dept_time.minute, train[i].arr_time.hour,
train[i].arr_time.minute);
}
}
printf ("\n");
break;
//List all the trains departed from particular station within the next one hour of
a given time.
case 3:
printf ("\n\t\t****INPUT DETAILS****\n");
printf ("Depart Station: ");
fflush (stdin);
gets (dept_st);
printf ("Time: \n");
printf ("Hour: ");
scanf ("%d", &train_time.hour);
printf ("Minute: ");
scanf ("%d", &train_time.minute);

//Print trains
for (i = 0; i <= no_of_trains - 1; i++)
{
if (strcmp (train[i].start_st, dept_st) == 0 &&
((train[i].dept_time.hour == train_time.hour
&& train[i].dept_time.minute >= train_time.minute)
|| (train[i].dept_time.hour == train_time.hour + 1
&& train[i].dept_time.minute <=
train_time.minute)))
{
printf ("%d\t\t%s\t%s\t%s\t%d:%d\t%d:%d\n", train[i].train_no,
train[i].train_name, train[i].start_st, train[i].end_st,
train[i].dept_time.hour,
train[i].dept_time.minute, train[i].arr_time.hour,
train[i].arr_time.minute);
}

}
printf ("\n");
break;
//List all the trains between a pair of start station and end station.
case 4:
printf ("\n\t\t****INPUT DETAILS****\n");
printf ("Depart Station: ");
fflush (stdin);
gets (dept_st);
printf ("Arrival Station: "); fflush
(stdin);
gets (arr_st);
//Print trains
for (i = 0; i <= no_of_trains - 1; i++)
{
if ((strcmp (train[i].start_st, dept_st) == 0) && (strcmp
(train[i].end_st, arr_st) == 0))
{
printf ("%d\t\t%s\t%s\t%s\t%d:%d\t%d:%d\n", train[i].train_no,
train[i].train_name, train[i].start_st, train[i].end_st,
train[i].dept_time.hour,
train[i].dept_time.minute, train[i].arr_time.hour,
train[i].arr_time.minute);
}
}
printf ("\n");
break;

//Edit train details. Call for train_edit case


5:
printf ("\n");
train_edit (train, &no_of_trains);
break;

//Exit
case 6:
return 0;
//Wrong Choice
default:
printf ("\nError! Wrong Choice.\n\n");
}
}

return 0;
}
void train_edit (TRAIN *train, int *no_of_trains)
{
int choice;
int i, train_num;
TRAIN temp;

while (1)
{
//Display Train Edit Menu
printf ("\t\t****TRAIN EDIT MENU****\n");
printf ("1. Add Train.\n");
printf ("2. Delete Train.\n");
printf ("3. Exit Train Edit Menu.\n"); printf
("Your Choice: ");

//Input choice
scanf ("%d", &choice);
switch (choice)
{
//Add Train
case 1:
//Already maximum
trains. if (*no_of_trains
>= MAX)
{
printf ("\nError! There are already maximum trains.\n\n");
break;
}
//Input train details in temp variable.
printf ("\nInput Train Number: "); scanf
("%d", &temp.train_no);

//Check if train number already exist or not.


for (i = 0; i <= *no_of_trains - 1; i++)
{
if (train[i].train_no == temp.train_no)
{
printf ("Error! Train number %d already exist. Please try
again.\n\n");
temp.train_no = -1;
break;
}
}
if (temp.train_no == -1)
break;

printf ("Input Train Name: ");


fflush (stdin);
gets (temp.train_name);
printf ("Input Start Station: ");
fflush (stdin);
gets (temp.start_st);
printf ("Input End Station: "); fflush
(stdin);
gets (temp.end_st);
printf ("Input Departure Time: \n");
printf ("Hour: ");
scanf ("%d",
&temp.dept_time.hour); printf
("Minute: ");
scanf ("%d",
&temp.dept_time.minute); printf
("Input Arrival Time: \n"); printf
("Hour: ");
scanf ("%d",
&temp.arr_time.hour); printf
("Minute: ");
scanf ("%d", &temp.arr_time.minute);
//Add temp into sorted array.
train[*no_of_trains] = temp;
for (i = *no_of_trains; i >= 1; i--)
{
if (train[i - 1].train_no >= train[i].train_no)
{
temp = train[i - 1];
train[i - 1] = train[i];
train[i] = temp;
}
else
break;
}
*no_of_trains = *no_of_trains + 1;
printf ("Train %d added successfully.\n\n", train[i].train_no); break;

//Delete Train
case 2:
//No train available. if
(*no_of_trains == 0)
{
printf ("\nError! No Train Available.\n\n"); break;
}

//Input train details.


printf ("\nInput Train Number: ");
scanf ("%d", &train_num);
//Find and delete train.
for (i = 0; i <= *no_of_trains - 1; i++)
{
if (train[i].train_no == train_num)
{
while (i <= *no_of_trains - 1)
{
train[i] = train[i + 1]; i++;
}
*no_of_trains = *no_of_trains - 1;
printf ("Train %d deleted successfully.\n\n", train_num);
train_num = -1;
break;
}
}
//Train not found. if
(train_num != -1)
printf ("Error! Train %d not found\n\n", train_num);
break;
//Exit Train Edit Menu
case 3:
printf ("\n");
return;
//Wrong choice
default:
printf ("\nError! Wrong Choice.\n\n");
}
}
}

Sample Output:
****TRAIN EDIT MENU****
1. Add Train.
2. Delete Train.
3. Exit Train Edit Menu.
Your Choice: 1
Input Train Number: 14511
Input Train Name: Nauchandi Express
Input Start Station: Prayagraj
Input End Station: Saharanpur
Input Departure Time:
Hour: 10
Minute: 15
Input Arrival Time:
Hour: 23
Minute: 10
Train 14511 added successfully.

****TRAIN EDIT MENU****


1. Add Train.
2. Delete Train.
3. Exit Train Edit Menu.
Your Choice: 1

Input Train Number: 14163


Input Train Name: Sangam Express
Input Start Station: Prayagraj
Input End Station: Meerut
Input Departure Time:
Hour: 10
Minute: 31
Input Arrival Time:
Hour: 21
Minute: 17
Train 14163 added successfully.

****TRAIN EDIT MENU****


1. Add Train.
2. Delete Train.
3. Exit Train Edit Menu.
Your Choice: 1

Input Train Number: 12687


Input Train Name: Dehradun Express
Input Start Station: New Delhi
Input End Station: Dehradun
Input Departure Time:
Hour: 9
Minute: 10
Input Arrival Time:
Hour: 16
Minute: 45
Train 12687 added successfully.

****TRAIN EDIT MENU****


1. Add Train.
2. Delete Train.
3. Exit Train Edit Menu.
Your Choice: 3

****MENU****
1. List all the trains departed from a particular station.
2. List all the trains departed from a particular station at a particular time.
3. List all the trains departed from particular station within the next one hour of a given
time.
4. List all the trains between a pair of start station and end station.
5. Edit train details.
6. Exit.
Your choice: 1

****INPUT
DETAILS**** Depart Station:
Prayagraj
14163 Sangam Express Prayagraj Meerut 10:31 21:17
14511 Nauchandi Prayagraj Saharanpur 10:15 23:10
Express

****MENU****
1. List all the trains departed from a particular station.
2. List all the trains departed from a particular station at a particular time.
3. List all the trains departed from particular station within the next one hour of a given
time.
4. List all the trains between a pair of start station and end station.
5. Edit train details.
6. Exit.
Your choice: 2

****INPUT
DETAILS**** Depart Station:
Prayagraj Train Time:
Hour: 10
Minute: 15
14511 Nauchandi Express Prayagraj Saharanpur 10:15 23:10

****MENU****
1. List all the trains departed from a particular station.
2. List all the trains departed from a particular station at a particular time.
3. List all the trains departed from particular station within the next one hour of a given
time.
4. List all the trains between a pair of start station and end station.
5. Edit train details.
6. Exit.
Your choice: 3

****INPUT
DETAILS**** Depart Station:
Prayagraj Time:
Hour: 10
Minute: 10
14163 Sangam Express Prayagraj Meerut 10:31 21:17
14511 Nauchandi Express Prayagraj Saharanpur 10:15 23:10

****MENU****
1. List all the trains departed from a particular station.
2. List all the trains departed from a particular station at a particular time.
3. List all the trains departed from particular station within the next one hour of a given
time.
4. List all the trains between a pair of start station and end station.
5. Edit train details.
6. Exit.
Your choice: 4

****INPUT
DETAILS**** Depart Station:
New Delhi Arrival Station:
Dehradun
12687 Dehradun Express New Delhi Dehradun 9:10 16:45

****MENU****
1. List all the trains departed from a particular station.
2. List all the trains departed from a particular station at a particular time.
3. List all the trains departed from particular station within the next one hour of a given
time.
4. List all the trains between a pair of start station and end station.
5. Edit train details.
6. Exit.
Your choice: 6
30. WAP to swap two elements using the concept of pointers.
#include <stdio.h>

void swap(int *a, int *b);

int main() {
int x = 5, y = 10;

printf("Before swapping: x = %d, y = %d\n", x, y);

swap(&x, &y);

printf("After swapping: x = %d, y = %d\n", x, y);

return 0;
}

void swap(int *a, int *b)


{ int temp = *a;
*a = *b;
*b = temp;
}
Output:
Before swapping: x = 5, = 10
y
After swapping: x = 10, = 5
y
31. WAP to compare the contents of two files and determine whether they are same or not
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE
100
int compare_files(FILE *file1, FILE *file2);
int main() {
FILE *file1, *file2;
char filename1[MAX_SIZE],
filename2[MAX_SIZE]; int is_same;
// Get the file names from the user
printf("Enter the first file name: ");
scanf("%s", filename1);
printf("Enter the second file name: ");
scanf("%s", filename2);
// Open the files for reading
file1 = fopen(filename1, "r");
file2 = fopen(filename2, "r");

if (file1 == NULL || file2 == NULL)


{ printf("Error: Unable to open files!\n");
exit(EXIT_FAILURE);
}
// Compare the files
is_same = compare_files(file1, file2);

// Print the result if


(is_same) {
printf("The contents of the two files are the same.\n");
} else {
printf("The contents of the two files are different.\n");
}
// Close the files
fclose(file1);
fclose(file2);

return 0;
}
int compare_files(FILE *file1, FILE *file2) {
char ch1, ch2;

// Read each character from both files and compare


them do {
ch1 = fgetc(file1);
ch2 = fgetc(file2);
if (ch1 != ch2) {
return 0;
}

} while (ch1 != EOF && ch2 != EOF);


// If both files have reached the end and there is no difference found if
(ch1 == EOF && ch2 == EOF) {
return 1;
} else {
return 0;
}
}
Sample output:

Enter the first file name: file1.txt Enter


the second file name: file2.txt
The contents of the two files are different.

Enter the first file name: file1.txt Enter


the second file name: file3.txt
The contents of the two files are the same.
32. WAP to check whether a given word exists in a file or not. If yes then find the number
of times it occurs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define
MAX_WORD_LENGTH 100
int main()
{
char filename[MAX_WORD_LENGTH],
word[MAX_WORD_LENGTH]; printf("Enter the filename:
");
scanf("%s", filename);
printf("Enter the word to search: ");
scanf("%s", word);
FILE *fp;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
int count = 0;
char buffer[MAX_WORD_LENGTH];
while (fscanf(fp, "%s", buffer) != EOF) { if
(strcmp(buffer, word) == 0) {
count++;
}
}
fclose(fp);
if (count > 0) {
printf("The word \"%s\" occurs %d time(s) in the file.\n", word, count);
} else {
printf("The word \"%s\" does not exist in the file.\n", word);
}

return 0;
}

Sample output:

Enter the filename: input.txt


Enter the word to search: the
The word "the" occurs 3 time(s) in the file.

You might also like