cadem Year: 2025-26 Semester: I Scheme: P25
Course Title: C Programming Laboratory
Course Code: P25PSCL1065 CIE Marks:50 CIE
Weightage:50%
Teaching hours/week (L:T:P):0:0:2 SEE Marks:50 SEE
Weightage:50%
Teaching hours of Pedagogy:24 Exam Hours: 3
Credits:1
Course outcome
At the end of the course, the student will be able to:
CO1: Develop programs in C to solve simple computational problems.
CO2: Make use of C language derived datatypes to solve simple real-world problems.
CO3: Build a document consisting of experiment setup, design, implementation and results with inferences.
Note:
1. The laboratory syllabus consists of PART-A and PART-B. While PART-A has 6 conventional experiments,
PART-B has 6 typical open-ended experiments. The maximum marks for the laboratory course are 100.
2. Both PART-A and PART-B are considered for CIE and SEE.
3. Students have answer 1(one) question from PART-A and 1(one) question from PART-B.
a. The questions set for SEE shall be from among the experiments under PART-A. It is evaluated for 70
marks out of the maximum 100 marks.
b. The open-ended question set for SEE shall be any other open-ended question and not selected from the
experiments under PART-A. It shall be evaluated for 30 marks.
4. For continuous internal evaluation, during the semester, classwork, the typical open-ended questions
shall be from PART-B, and any other similar questions to enhance the skill of the students
PART – A CONVENTIONAL EXPERIMENTS
Note: Students must write the algorithm & flowchart for PART-A questions in the Record book
1. A robot needs to find how far it must travel between two points on a 2D plane. Develop a C program to
calculate the straight-line distance between the given coordinates.
2. Develop a C program that takes a student's marks as input and displays their grade based on the
following criteria:
90 and above:
Grade A 75 to
89: Grade B
60 to 74: Grade C
50 to 59: Grade
D Below 50:
Grade F
Choose a suitable control structure to implement this logic efficiently.
3. Develop a C program that takes a unique identification input like PAN Number, AADHAR_Number,
APAAR_Id, Driving License, Passport and checks it against a set of stored KYC records. Based on the
input, display whether the individual is verified or not. Use an appropriate control structure to handle
multiple possible ID matches. Assume all Unique identification are of integer type.
4. A math app needs to determine the type of roots for a quadratic equation based on user input. Develop
a C program to calculate and display the roots based on the given coefficients.
5. A sensor in a robotic arm needs to calculate the angle of rotation in real-time, but the hardware doesn't
support built-in trigonometric functions. Develop a C program to approximate the value of sin(x) using
a series expansion method for improved performance.
6. Develop a C program that accepts a course description string and a keyword from the user. Search
whether the keyword exists within the course description using appropriate string functions. If found,
display: "Keyword '<keyword>' found in the course description." Otherwise, display: "Keyword
'<keyword>' not found in the course description."
7. Develop a C program that takes marks for three subjects as input. Use a function to check if the student
has passed (minimum 40 marks in each subject). Display the average and whether the student passed or
failed.
8. In an ATM system, two account balances need to be swapped temporarily for validation. Develop a C
program that accepts two balances and uses a function with pointers to swap them. Display the balances
before and after swapping.
PART – B
TYPICAL OPEN-ENDED EXPERIMENTS
Open-ended experiments are a type of laboratory activity where the outcome is not predetermined, and students are
given the freedom to explore, design, and conduct the experiment based on the problem statements as per the concepts
defined by the course coordinator. It encourages creativity, critical thinking, and inquiry-based learning.
1. A college library has a digital bookshelf system where each book is assigned a unique Book ID. The bookshelf is
organized in ascending order of Book IDs. Develop a C Program to quickly find whether a book with a specific
Book ID is available in the shelf.
2. A sports teacher has recorded the scores of students in a 100-meter race. To prepare the result sheet, the teacher
wants the scores arranged in descending order (from highest to lowest). Develop a C program to sort the scores.
3. A small warehouse tracks how many units of different products are shipped from multiple branches. Another
dataset shows how much revenue each product generates per unit. Develop a C program which combines these
datasets to calculate the total revenue generated by each branch.
4. A basic mobile contact manager stores first and last names separately. For displaying full names in the contact
list, you need to join them manually. Additionally, the system must check the length of each full name to ensure it
fits the screen. Perform these operations by developing a C program without using built- in string functions.
5. A currency exchange booth allows users to convert between two currencies. Before confirming the exchange, the
system simulates a swap of the values to preview the result without actually changing the original data. In other
cases, it updates the actual values. Develop a C program that implements both behaviours using Call by Value and
Call by reference
6. A local library needs to store and display details of its books, including title, author, and year of publication.
Design a structure that can hold these details and develop a C program to display a list of all books entered.
Problem 1:
A robot needs to find how far it must travel between two points on a 2D plane. Develop a C
program to calculate the straight-line distance between the given coordinates.
Solution:
Each point is represented as (x,y)
First point : (x1,y1)
Second point:(x2,y2)
For two points on a 2D plane:
𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒 = 𝑠𝑞𝑟𝑡((𝑥2 − 𝑥1)2 + (𝑦2 − 𝑦1)2 )
distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)
Algorithm: Calculate Straight-Line Distance Between Two Points
Step 1: Start
Step 2: Declare variables x1, y1, x2, y2 (coordinates) and distance (result).
Step 3: Read the first point coordinates x1 and y1 from the user.
Step 4: Read the second point coordinates x2 and y2 from the user.
Step 5: Compute the difference in x: dx = x2 – x1.
Step 6: Compute the difference in y: dy = y2 – y1.
Step 7: Compute the square of the differences:
dx² = (x2 – x1)²
dy² = (y2 – y1)²
Step 8: Add the squares: sum = dx² + dy².
Step 9: Compute the square root of the sum to find the distance:
distance = √(sum)
Step 10: Display the value of distance.
Step 11: Stop.
Program:
#include <stdio.h>
#include <math.h> // for sqrt( ) and pow( )
int main( )
{
double x1, y1, x2, y2, distance;
// Input coordinates
printf("Enter x1 and y1: ");
scanf("%lf %lf", &x1, &y1);
printf("Enter x2 and y2: ");
scanf("%lf %lf", &x2, &y2);
// Calculate distance using Euclidean formula
distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
// Output the result
printf("Straight-line distance: %lf\n", distance);
return 0;
}
Sample input and output:
Enter x1 and y1: 2 3
Enter x2 and y2: 7 8
Straight-line distance: 7.0
Problem 2:
Develop a C program that takes a student's marks as input and displays their grade based on the
following criteria:
90 and above:Grade A
75 to 89: Grade B
60 to 74: Grade C
50 to 59: Grade D
Below 50: Grade F
Choose a suitable control structure to implement this logic efficiently.
Algorithm:
Step 1: Start
Step 2: Declare an integer variable marks.
Step 3: Read marks from the user.
Step 4:
Use an if…else if…else ladder to check the grade:
if marks >= 90 → print “Grade A”.
else if marks >= 75 → print “Grade B”.
else if marks >= 60 → print “Grade C”.
else if marks >= 50 → print “Grade D”.
else → print “Grade F”.
Step 5: Stop.
Program :
#include <stdio.h>
int main( )
{
int marks;
// Input marks
printf("Enter student's marks: ");
scanf("%d", &marks);
// Grade decision using if-else ladder
if (marks >= 90)
{
printf("Grade A\n");
}
else if (marks >= 75)
{
printf("Grade B\n");
}
else if (marks >= 60)
{
printf("Grade C\n");
}
else if (marks >= 50)
{
printf("Grade D\n");
}
else
{
printf("Grade F\n");
}
return 0;
}
Sample input and output 1:
Enter student's marks: 92
Grade A
Sample input and output 2:
Enter student's marks: 77
Grade B
Problem 3:
Develop a C program that takes a unique identification input like PAN Number,
AADHAR_Number, APAAR_Id, Driving License, Passport and checks it against a set of stored
KYC records. Based on the input, display whether the individual is verified or not. Use an
appropriate control structure to handle multiple possible ID matches. Assume all Unique
identification are of integer type.
Algorithm:
Step 1: Start
Step 2: Declare arrays for PAN numbers, AADHAR numbers, APAAR IDs, Driving Licenses,
and Passports.
Step 3: Prompt the user to select an ID type.
Step 4: Prompt the user to enter the ID number.
Step 5: Initialize a flag variable verified = 0.
Step 6:
Use switch(choice) to handle the selected ID type:
For each case, loop through the corresponding array:
o If inputID matches any stored ID, set verified = 1 and break.
Step 7:
if verified == 1, print “Individual is VERIFIED”.
else, print “Individual is NOT VERIFIED”.
Step 8: Stop.
Program:
#include <stdio.h>
int main( )
{
// Stored KYC records (dummy data as integers)
int panNumbers[] = {10101, 10102, 10103};
int aadharNumbers[] = {20201, 20202, 20203};
int apaarIds[] = {30301, 30302, 30303};
int drivingLicenses[] = {40401, 40402, 40403};
int passports[] = {50501, 50502, 50503};
int i, inputID, choice;
int size = 3; // number of records in each list
printf("Select ID type to verify:\n");
printf("1. PAN Number\n");
printf("2. AADHAR Number\n");
printf("3. APAAR ID\n");
printf("4. Driving License\n");
printf("5. Passport\n");
printf("Enter your choice: ");
scanf("%d", &choice);
printf("Enter the unique ID number: ");
scanf("%d", &inputID);
int verified = 0; // flag
// Using switch-case to handle multiple ID types
switch (choice)
{
case 1:
for (i = 0; i < size; i++)
{
if (inputID == panNumbers[i])
{
verified = 1;
break;
}
}
break;
case 2:
for (i = 0; i < size; i++)
{
if (inputID == aadharNumbers[i])
{
verified = 1;
break;
}
}
break;
case 3:
for (i = 0; i < size; i++)
{
if (inputID == apaarIds[i])
{
verified = 1;
break;
}
}
break;
case 4:
for (i = 0; i < size; i++)
{
if (inputID == drivingLicenses[i])
{
verified = 1;
break;
}
}
break;
case 5:
for (i = 0; i < size; i++)
{
if (inputID == passports[i])
{
verified = 1;
break;
}
}
break;
default:
printf("Invalid choice!\n");
return 0;
}
if (verified)
printf(" Individual is VERIFIED.\n");
else
printf("individual is NOT VERIFIED.\n");
return 0;
}
Sample Input and Output:
Select ID type to verify:
1. PAN Number
2. AADHAR Number
3. APAAR ID
4. Driving License
5. Passport
Enter your choice: 2
Enter the unique ID number: 20203
Individual is VERIFIED.
Problem 4:
A math app needs to determine the type of roots for a quadratic equation based on user input.
Develop a C program to calculate and display the roots based on the given coefficients.
Algorithm:
Step 1: Start
Step 2: Declare variables
a, b, c (coefficients)
discriminant (to store b2−4acb^2 - 4acb2−4ac)
root1, root2 (to store real roots)
realPart, imagPart (to store real and imaginary parts of complex roots).
Step 3: Prompt the user to enter coefficients a, b, and c.
Read the input values.
Step 4: If a == 0, print “Not a quadratic equation” and terminate the program.
Step 5: Calculate discriminant:
discriminant = b*b - 4*a*c
Step 6:
if discriminant > 0
o Roots are real and distinct.
o Compute:
root1 = (-b + sqrt(discriminant)) / (2*a)
root2 = (-b - sqrt(discriminant)) / (2*a)
Print both roots.
else if discriminant == 0
Roots are real and equal.
Compute:
root1 = root2 = -b / (2*a)
Print the root.
else
Roots are complex.
Compute:
realPart = -b / (2*a)
imagPart = sqrt(-discriminant) / (2*a)
Print both complex roots as:
root1 = realPart + imagPart i
root2 = realPart - imagPart i
Step 7: Stop.
Program:
#include <stdio.h>
#include <math.h> // for sqrt( )
int main( )
{
float a, b, c;
float discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
if (a == 0)
{
printf("Not a quadratic equation (a cannot be 0).\n");
return 0;
}
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\n");
printf("Root1 = %.2f and Root2 = %.2f\n", root1, root2);
}
else if (discriminant == 0)
{
// Real and equal roots
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal.\n");
printf("Root1 = Root2 = %.2f\n", root1);
}
else
{
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex \n");
printf("Root1 = %.2f + %.2f i and Root2 = %.2f - %.2f i\n", realPart, imagPart, realPart,
imagPart);
}
return 0;
}
Sample Input and Output :
Enter coefficients a, b and c: 1 5 6
Roots are real and distinct.
Root1 = -2.00 and Root2 = -3.00
Sample input and output:
Enter coefficients a, b and c: 1 2 5
Roots are complex
Root1 = -1.00 + 2.00i and Root2 = -1.00 - 2.00i
Program 5
A sensor in a robotic arm needs to calculate the angle of rotation in real-time, but the hardware
doesn't support built-in trigonometric functions. Develop a C program to approximate the value
of sin(x) using a series expansion method for improved performance.
Sin(x) = x – x3/ 3! + x5/5! - x7/7! + x9/9!..........................
Algorithm:
Step 1: Start
Step 2: Define the constant PI = 3.142
Step 3: Declare variables:
int n, i for number of terms and loop index
float deg, x, sum, term
Step 4: Prompt and read n (number of terms) from user
Step 5: Prompt and read deg (angle in degrees) from user
Step 6: Convert angle to radians:
x = (deg * PI) / 180
Step 7: Initialize:
term = x
sum = term
Step 8: For i from 3 to n with step 2, repeat:
Update term: term = (-term * x * x) / (i * (i - 1))
Update sum: sum = sum + term
Step 9: Display:
The angle in radians
The value of sin(deg) using Taylor series (sum)
The value of sin(deg) using the inbuilt sin(x) function
Step 10: Stop
Program:
#include <math.h>
#include <stdio.h>
#include <conio.h>
#define PI 3.142
int main( )
{
int n, i;
float deg, x, sum = 0, term = 0;
printf("Enter number of terms, say n\n");
scanf("%d", &n);
printf("Enter the degree\n");
scanf("%f", °);
x = (deg * PI) / 180;
printf("In Radians = %f \n", x);
term = x;
sum = term;
for (i = 3; i <= n; i += 2)
{
term = (-term * x * x) / (i * (i - 1));
sum = sum + term;
}
printf("sin(%f)=%f\n", deg, sum);
printf("Inbuilt function Sin(%f) = %f \n", deg, sin(x));
printf("User function Sin(%f) = %f", deg, sum);
}
Sample Input and Output:
Enter number of terms, say n 3
Enter the degree 90
In Radians = 1.571000
Sin(90.000)= 0.924785
Inbuilt function Sin(90.0000)=1.0000000000
Use function Sin(90.0000)=0.924785
Program 6
Develop a C program that accepts a course description string and a keyword from the user.
Search whether the keyword exists within the course description using appropriate string
functions. If found, display: "Keyword '<keyword>' found in the course description."
Otherwise, display: "Keyword '<keyword>' not found in the course description."
Algorithm:
Step 1: Start
Step 2: Declare two character arrays:
course[200] → to store the course description
keyword[50] → to store the keyword
Step 3: Prompt the user to enter the course description and read it using gets(course)
Step 4: Prompt the user to enter the keyword and read it using scanf("%s", keyword)
Step 5: Check if the keyword exists in the course description:
Use strstr(course, keyword) function
If the function returns not NULL, then the keyword is found
Else, the keyword is not found
Step 6: Display the result:
If found → Print "Keyword '<keyword>' found in the course description."
If not found → Print "Keyword '<keyword>' not found in the course
description."
Step 7: Stop
Program :
#include <stdio.h>
#include <string.h>
int main( )
{
char course[200], keyword[50];
// Input the course description using gets()
printf("Enter the course description: ");
gets(course);
// Input the keyword
printf("Enter the keyword to search: ");
scanf("%s", keyword);
// Search the keyword in the course description
if (strstr(course, keyword) != NULL)
{
printf("Keyword '%s' found in the course description.\n", keyword);
}
else
{
printf("Keyword '%s' not found in the course description.\n", keyword);
}
return 0;
}
Sample Input and Output 1:
Enter the course description: C Programming Lab Course
Enter the keyword to search: Lab
Keyword 'Lab' found in the course description.
Sample Input and Output 2:
Enter the course description: C Programming Lab Course
Enter the keyword to search: Python
Keyword 'Python' not found in the course description.
Problem 7:
Develop a C program that takes marks for three subjects as input. Use a function to check if the
student has passed (minimum 40 marks in each subject). Display the average and whether the student
passed or failed.
Algorithm:
Step 1: Start
Step 2: Declare variables:
int marks1, marks2, marks3 → to store marks of three subjects
float average → to store average marks
Step 3: Prompt the user to enter marks for three subjects and read them
Step 4: Calculate average:
average=marks1 + marks2 + marks33.0\text{average} = \frac{\text{marks1 + marks2 +
marks3}}{3.0}average=3.0marks1 + marks2 + marks3
Step 5: Call a function checkPass(m1, m2, m3) which:
Returns 1 if all marks ≥ 40
Returns 0 otherwise
Step 6: Display the average
Step 7: If checkPass returned 1 → Print “Passed”
Else → Print “Failed”
Step 8: Stop
Program:
#include <stdio.h>
// Function to check if student passed
int checkPass(int m1, int m2, int m3)
{
if (m1 >= 40 && m2 >= 40 && m3 >= 40)
return 1; // Passed
else
return 0; // Failed
}
int main( )
{
int marks1, marks2, marks3;
float average;
// Input marks
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);
// Calculate average
average = (marks1 + marks2 + marks3) / 3.0;
// Display average
printf("Average marks = %.2f\n", average);
// Check pass/fail
if (checkPass(marks1, marks2, marks3))
printf("Student Passed\n");
else
printf("Student Failed\n");
return 0;
}
Sample input and output 1:
Enter marks for Subject 1: 55
Enter marks for Subject 2: 70
Enter marks for Subject 3: 80
Average marks = 68.33
Student Passed
Sample input and output 2:
Enter marks for Subject 1: 35
Enter marks for Subject 2: 60
Enter marks for Subject 3: 50
Average marks = 48.33
Student Failed
Problem :8
In an ATM system, two account balances need to be swapped temporarily for validation. Develop a C
program that accepts two balances and uses a function with pointers to swap them. Display the
balances before and after swapping.
Algorithm:
Step 1: Start
Step 2: Declare two variables: balance1 and balance2
Step 3: Prompt the user to enter the two balances and read them
Step 4: Display balances before swapping
Step 5: Call a function swapBalances(float *a, float *b) which swaps the values using
pointers:
Use a temporary variable temp
temp = *a
*a = *b
*b = temp
Step 6: Display balances after swapping
Step 7: Stop
Program:
#include <stdio.h>
// Function to swap two balances using pointers
void swapBalances(float *a, float *b)
{
float temp = *a;
*a = *b;
*b = temp;
}
int main( )
{
float balance1, balance2;
// Input balances
printf("Enter balance of Account 1: ");
scanf("%f", &balance1);
printf("Enter balance of Account 2: ");
scanf("%f", &balance2);
// Display before swapping
printf("\nBalances before swapping:\n");
printf("Account 1: %.2f\n", balance1);
printf("Account 2: %.2f\n", balance2);
// Swap using function
swapBalances(&balance1, &balance2);
// Display after swapping
printf("\nBalances after swapping:\n");
printf("Account 1: %.2f\n", balance1);
printf("Account 2: %.2f\n", balance2);
return 0;
}
Sample input and ouput:
Enter balance of Account 1: 2500.50
Enter balance of Account 2: 4000.75
Balances before swapping:
Account 1: 2500.50
Account 2: 4000.75
Balances after swapping:
Account 1: 4000.75
Account 2: 2500.50
Part B
Problem 1
A college library has a digital bookshelf system where each book is assigned a unique Book
ID. The bookshelf is organized in ascending order of Book IDs. Develop a C Program to
quickly find whether a book with a specific Book ID is available in the shelf.
Algorithm:
Step 1: Start
Step 2: Declare:
An integer array books[] to store Book IDs (assume sorted in ascending order)
int n → number of books
int key → Book ID to search
Step 3: Prompt the user to enter the Book IDs in ascending order (or use pre-stored IDs)
Step 4: Prompt the user to enter the Book ID to search (key)
Step 5: Initialize low = 0 and high = n - 1
Step 6: While low <= high:
Compute mid = (low + high) / 2
If books[mid] == key → Book found, print message and stop
If books[mid] < key → low = mid + 1
Else → high = mid - 1
Step 7: If the loop ends without finding → print “Book not found”
Step 8: Stop
Program:
#include <stdio.h>
int main( )
{
int n, key;
// Input number of books
printf("Enter number of books: ");
scanf("%d", &n);
int books[n];
// Input book IDs in ascending order
printf("Enter %d Book IDs in ascending order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &books[i]);
}
// Input Book ID to search
printf("Enter Book ID to search: ");
scanf("%d", &key);
// Binary search
int low = 0, high = n - 1, found = 0;
while (low <= high)
{
int mid = (low + high) / 2;
if (books[mid] == key)
{
found = 1;
break;
}
else if (books[mid] < key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
// Display result
if (found)
{
printf("Book with ID %d is available in the shelf.\n", key);
}
else
{
printf("Book with ID %d is NOT available in the shelf.\n", key);
}
return 0;
}
Sample input and output 1:
Enter number of books: 5
Enter 5 Book IDs in ascending order:
101 203 305 407 509
Enter Book ID to search: 305
Book with ID 305 is available in the shelf.
Sample input and output 2:
Enter number of books: 5
Enter 5 Book IDs in ascending order:
101 203 305 407 509
Enter Book ID to search: 50
Book with ID 50 is NOT available in the shelf.
Problem 2:
A sports teacher has recorded the scores of students in a 100-meter race. To prepare the result
sheet, the teacher wants the scores arranged in descending order (from highest to lowest).
Develop a C program to sort the scores.
Algorithm:
Step 1: Start
Step 2: Declare:
int n → number of students
int scores[n] → array to store scores
Step 3: Input number of students and their scores
Step 4: Use a nested loop to sort the scores in descending order:
For each i from 0 to n-2:
o For each j from 0 to n-i-2:
If scores[j] < scores[j+1], swap them
Step 5: Display the scores after sorting
Step 6: Stop
Program:
#include <stdio.h>
int main( )
{
int n;
// Input number of students
printf("Enter number of students: ");
scanf("%d", &n);
int scores[n];
// Input scores
printf("Enter scores of %d students:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &scores[i]);
}
// Sort in descending order (Bubble Sort)
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (scores[j] < scores[j + 1])
{
int temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
// Display sorted scores
printf("Scores in descending order:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", scores[i]);
}
printf("\n");
return 0;
}
Sample Input and Output 1 :
Enter number of students: 5
Enter scores of 5 students:
45 72 88 60 50
Scores in descending order:
88 72 60 50 45
Problem 3:
A small warehouse tracks how many units of different products are shipped from multiple branches.
Another dataset shows how much revenue each product generates per unit. Develop a C program
which combines these datasets to calculate the total revenue generated by each branch.
Algorithm:
Step 1: Start
Step 2: Declare variables:
int units[branches][products] → units shipped
float revenuePerUnit[products] → revenue per unit for each product
float totalRevenue[branches] → total revenue per branch
Step 3: Input:
Number of branches and number of products
Units shipped by each branch for each product
Revenue per unit for each product
Step 4: Initialize totalRevenue[branch] = 0
Step 5: For each branch i:
For each product j:
o totalRevenue[i] += units[i][j] * revenuePerUnit[j]
Step 6: Display total revenue for each branch
Step 7: Stop
Program:
#include <stdio.h>
int main( )
{
int branches, products;
// Input number of branches and products
printf("Enter number of branches: ");
scanf("%d", &branches);
printf("Enter number of products: ");
scanf("%d", &products);
int units[branches][products];
float revenuePerUnit[products];
float totalRevenue[branches];
// Input units shipped for each branch
printf("Enter units shipped by each branch for each product:\n");
for (int i = 0; i < branches; i++)
{
printf("Branch %d:\n", i + 1);
for (int j = 0; j < products; j++)
{
scanf("%d", &units[i][j]);
}
}
// Input revenue per unit for each product
printf("Enter revenue per unit for each product:\n");
for (int j = 0; j < products; j++)
{
scanf("%f", &revenuePerUnit[j]);
}
// Calculate total revenue per branch
for (int i = 0; i < branches; i++)
{
totalRevenue[i] = 0;
for (int j = 0; j < products; j++)
{
totalRevenue[i] += units[i][j] * revenuePerUnit[j];
}
}
// Display total revenue
printf("\nTotal revenue generated by each branch:\n");
for (int i = 0; i < branches; i++)
{
printf("Branch %d: %.2f\n", i + 1, totalRevenue[i]);
}
return 0;
}
Sample Input and Output 1:
Enter number of branches: 2
Enter number of products: 3
Enter units shipped by each branch for each product:
Branch 1:
10 20 30
Branch 2:
5 15 25
Enter revenue per unit for each product:
2.5 4.0 3.0
Total revenue generated by each branch:
Branch 1: 220.00
Branch 2: 145.00
Problem 4
A basic mobile contact manager stores first and last names separately. For displaying full names in the
contact list, you need to join them manually. Additionally, the system must check the length of each
full name to ensure it fits the screen. Perform these operations by developing a C program without
using built- in string functions.
Algorithm :
Step 1: Start
Step 2: Declare two character arrays:
firstName[50]
lastName[50]
fullName[100]
Step 3: Input firstName and lastName from the user
Step 4: Concatenate firstName and lastName manually:
Initialize index i = 0
Copy characters from firstName to fullName
Append a space ' '
Copy characters from lastName to fullName
Terminate fullName with '\0'
Step 5: Calculate the length of fullName manually:
Initialize length = 0
Traverse fullName until '\0', increment length
Step 6: Display the fullName and its length
Step 7: If length exceeds screen limit (e.g., 20), display warning
Step 8: Stop
Program:
#include <stdio.h>
int main( )
{
char firstName[50], lastName[50], fullName[100];
int i, j, length;
// Input first and last names
printf("Enter first name: ");
scanf("%s", firstName);
printf("Enter last name: ");
scanf("%s", lastName);
// Concatenate manually
i = 0;
// Copy first name
while (firstName[i] != '\0')
{
fullName[i] = firstName[i];
i++;
}
// Add space
fullName[i] = ' ';
i++;
// Copy last name
j = 0;
while (lastName[j] != '\0')
{
fullName[i] = lastName[j];
i++;
j++;
}
// Terminate string
fullName[i] = '\0';
// Calculate length manually
length = 0;
while (fullName[length] != '\0')
{
length++;
}
// Display full name and length
printf("Full Name: %s\n", fullName);
printf("Length of Full Name: %d\n", length);
// Optional: check if it fits the screen
if (length > 20)
{
printf("Warning: Name exceeds screen limit!\n");
}
return 0;
}
Sample Input and Output 1:
Enter first name: John
Enter last name: Doe
Full Name: John Doe
Length of Full Name: 8
Problem 5
A currency exchange booth allows users to convert between two currencies. Before confirming the exchange,
the system simulates a swap of the values to preview the result without actually changing the original data. In
other cases, it updates the actual values. Develop a C program that implements both behaviours using Call by
Value and Call by reference.
Algorithm:
Step 1: Start
Step 2: Declare two float variables: currency1 and currency2
Step 3: Input the two currency amounts from the user
Step 4: Define a function simulateSwap(float a, float b)
Uses call by value
Swaps a and b inside the function
Displays the swapped values
Does NOT affect the original variables
Step 5: Define a function realSwap(float *a, float *b)
Uses call by reference (pointers)
Swaps *a and *b inside the function
Actually changes the original variables
Step 6: In main():
Call simulateSwap(currency1, currency2) to preview swap
Display original values to show they are unchanged
Call realSwap(¤cy1, ¤cy2) to actually swap
Display updated values to show they are swapped
Step 7: Stop
Program :
#include <stdio.h>
// Call by Value (simulated swap)
void simulateSwap(float a, float b)
{
float temp = a;
a = b;
b = temp;
printf("\n[Preview] After simulated swap inside function:\n");
printf("Currency 1: %.2f\nCurrency 2: %.2f\n", a, b);
}
// Call by Reference (actual swap)
void realSwap(float *a, float *b)
{
float temp = *a;
*a = *b;
*b = temp;
}
int main( )
{
float currency1, currency2;
// Input currency values
printf("Enter amount in Currency 1: ");
scanf("%f", ¤cy1);
printf("Enter amount in Currency 2: ");
scanf("%f", ¤cy2);
// Display before swap
printf("\nOriginal Values:\n");
printf("Currency 1: %.2f\nCurrency 2: %.2f\n", currency1, currency2);
// Simulated swap (Call by Value)
simulateSwap(currency1, currency2);
// Display after simulated swap (original values unchanged)
printf("\nAfter simulated swap (original values unchanged):\n");
printf("Currency 1: %.2f\nCurrency 2: %.2f\n", currency1, currency2);
// Real swap (Call by Reference)
realSwap(¤cy1, ¤cy2);
// Display after real swap (original values changed)
printf("\nAfter real swap (original values swapped):\n");
printf("Currency 1: %.2f\nCurrency 2: %.2f\n", currency1, currency2);
return 0;
}
Sample Input and Output:
Enter amount in Currency 1: 500.00
Enter amount in Currency 2: 800.00
Original Values:
Currency 1: 500.00
Currency 2: 800.00
[Preview] After simulated swap inside function:
Currency 1: 800.00
Currency 2: 500.00
After simulated swap (original values unchanged):
Currency 1: 500.00
Currency 2: 800.00
After real swap (original values swapped):
Currency 1: 800.00
Currency 2: 500.00
Problem 6:
A local library needs to store and display details of its books, including title, author, and year of publication.
Design a structure that can hold these details and develop a C program to display a list of all books entered.
Algorithm:
Step 1: Start
Step 2: Define a structure Book with members:
char title[100]
char author[100]
int year
Step 3: Ask the user for the number of books n
Step 4: For each book i from 0 to n–1:
Prompt and read title
Prompt and read author
Prompt and read year
Step 5: After input, display a table-like list of all books
Step 6: Stop
Program:
#include <stdio.h>
struct Book
char title[100];
char author[100];
int year;
};
int main( )
int n;
printf("Enter number of books: ");
scanf("%d", &n);
struct Book books[n];
// Input book details
for (int i = 0; i < n; i++)
{
printf("\nEnter details of Book %d:\n", i + 1);
// Clear input buffer for strings after scanf
getchar( ); // consume newline left in buffer
printf("Title: ");
fgets(books[i].title, sizeof(books[i].title), stdin);
// remove trailing newline from fgets
int len = 0;
while (books[i].title[len] != '\0')
if (books[i].title[len] == '\n')
books[i].title[len] = '\0';
break;
len++;
printf("Author: ");
fgets(books[i].author, sizeof(books[i].author), stdin);
// remove trailing newline
len = 0;
while (books[i].author[len] != '\0')
if (books[i].author[len] == '\n')
books[i].author[len] = '\0';
break;
len++;
printf("Year of Publication: ");
scanf("%d", &books[i].year);
// Display all books
printf("\nList of Books:\n");
printf("%-30s %-20s %-5s\n", "Title", "Author", "Year");
printf("--------------------------------------------------------------\n");
for (int i = 0; i < n; i++)
printf("%-30s %-20s %-5d\n", books[i].title, books[i].author, books[i].year);
return 0;
Sample Input and Output:
Enter number of books: 2
Enter details of Book 1:
Title: The C Programming Language
Author: Kernighan & Ritchie
Year of Publication: 1978
Enter details of Book 2:
Title: Clean Code
Author: Robert C. Martin
Year of Publication: 2008
Output:
List of Books:
Title Author Year
--------------------------------------------------------------
The C Programming Language Kernighan & Ritchie 1978
Clean Code Robert C. Martin 2008