0% found this document useful (0 votes)
28 views372 pages

Lab Files

Uploaded by

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

Lab Files

Uploaded by

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

Date: 2024-09-

Page No: 1
S.No: 1 Exp. Name: Speed Calculator
26

Aim:

ID: 247Y1A6790
Write a C program that should prompt the user to input the distance traveled and the
time taken and calculate the speed using the formula: Speed = Distance / Time.

Input Format:
• A single line which accepts the distance and time as space separated integers.

Output Format:
• Prints the speed as an integer output after calculating using the given formula
Source Code:

speedCalculator.c

2024-2028-CSD-B
#include<stdio.h>
void main()
{
int d,t,s;
scanf("%d%d",&d,&t);
s=d/t;
printf("%d",s);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
400 40
10

Test Case - 2

User Output
100 20
5
Date: 2024-09-
S.No: 2 Exp. Name: Area of a Circle

Page No: 2
26

Aim:
Write a C program that prompts the user to enter the radius of the circle and computes

ID: 247Y1A6790
the area of a circle.

Note:
• Take the Pi value as 3.14.
• Print the result up to 3 decimal places.

Input format:
The input is the floating point value that represents the radius of a circle.

Output format:
The output is the floating point value that represents the area of the circle.

2024-2028-CSD-B
Source Code:

circleArea.c
#include<stdio.h>
void main()
{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


float area,radius;
scanf("%f",&radius);
area=3.14*radius*radius;
printf("%.3f",area);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1.23
4.751

Test Case - 2

User Output
2.5
19.625

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 3
Date: 2024-10-
S.No: 3 Exp. Name: Fuel Efficiency Calculation

Page No: 4
03

Aim:
Write a C program that calculates the fuel efficiency of a vehicle. The program should

ID: 247Y1A6790
prompt the user to input the distance traveled and the amount of fuel consumed. The
fuel efficiency should be calculated in miles per gallon (MPG) using the formula: MPG =
Distance / Fuel Consumption.

Input Format
A single line of input containing two space-separated floating-point numbers:
• The first number represents the distance traveled (in miles).
• The second number represents the amount of fuel consumed (in gallons).

Output Format
Displays the fuel efficiency in miles per gallon (MPG) rounded to two decimal places.

2024-2028-CSD-B
Source Code:

mpgCalculator.c
#include<stdio.h>
void main()
{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


float distance,fuel;
scanf("%f%f",&distance,&fuel);
float mpg=distance/fuel;
printf("%.2f \n",mpg);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
200 20
10.00

Test Case - 2

User Output
200.4 15.6
12.85

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 5
Exp. Name: Calculation of the discount Date: 2024-10-
S.No: 4

Page No: 6
price 03

Aim:
Write a C program that calculates the discounted price of an item. The program should

ID: 247Y1A6790
prompt the user to input the original price and the discount percentage. The discounted
price should be calculated using the formula: Discounted Price = Original Price -
(Original Price * Discount Percentage /100).

Input Format
A single line of input containing two space-separated floating-point numbers.
• The first number represents the original price of the item.
• The second number represents the discount percentage.

Output Format
Displays the discounted price of the item rounded to two decimal places

2024-2028-CSD-B
Source Code:

discountPriceCalc.c
#include<stdio.h>
void main()
{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


float originalprice,discountpercent;
scanf("%f%f",&originalprice,&discountpercent);
float discountprice;
discountprice=originalprice-(originalprice*discountpercent/100);
printf("%.2f",discountprice);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
600 10
540.00

Test Case - 2

User Output
735.00
1050 30

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 7
Date: 2024-10-
S.No: 5 Exp. Name: Monthly Budget Tracker

Page No: 8
03

Aim:
Write a C program prompt the user to input their income and expenses and calculate the

ID: 247Y1A6790
total savings using the formula: Total Savings = Income - Total Expenses.

Input Format
A single line of input containing two space-separated floating-point numbers:
• The first number represents the income.
• The second number represents the expenses.

Output Format
Displays the savings of the month rounded to three decimal places
Source Code:

2024-2028-CSD-B
budgetCalculator.c
#include<stdio.h>
void main()
{
float income,expenses;
scanf("%f%f",&income,&expenses);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


float totalsavings;
totalsavings=income-expenses;
printf("%.3f",totalsavings);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
30000 20000
10000.000

Test Case - 2

User Output
55000 30000
25000.000
Exp. Name: Loan amortization Date: 2024-10-
S.No: 6

Page No: 9
calculator 03

Aim:
Write a C program that calculates the monthly payment for a loan. The program should

ID: 247Y1A6790
prompt the user to input the loan amount, interest rate, and loan duration. The monthly
payment should be calculated using the formula: Monthly Payment = (Loan Amount *
Interest Rate * (1+ Interest Rate) ) / ((1 + Interest Rate)
Duration Duration−1
).

Input Format
• First Line : A floating-point number that represents the total amount of the loan.
• Second Line : A floating-point number that represents the monthly interest rate (as
a decimal). For example, 5% interest rate should be entered as 0.05.
• Third Line : An integer representing the number of months over which the loan will
be repaid.

2024-2028-CSD-B
Output Format
• Displays the calculated monthly payment rounded to two decimal places.

Note: Use math library pow() function for the calculation.


Source Code:

loanCalculator.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
#include<math.h>
void main()
{
float totalamt;
float rate;
int months;
scanf("%f%f",&totalamt,&rate);
scanf("%d",&months);
float monthlypayment;
monthlypayment=
(totalamt*rate*pow((1+rate),months))/(pow((1+rate),months)-1);
printf("%.2f",monthlypayment);
}

Execution Results - All test cases have succeeded!


Test Case - 1
12
60

0.01
0.005

10000
50000

888.49
966.64

User Output
User Output

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 10
Date: 2024-10-
S.No: 7 Exp. Name: Surface Area of Room

Page No: 11
03

Aim:
You need to calculate the surface area of a rectangular room. The surface area can be

ID: 247Y1A6790
calculated using the formula: Surface Area = 2 * (Length * Width + Length * Height
+Width * Height).
Write a C program that prompts the user to input the length, width, and height of the
room and calculates the surface area using the above formula.

Input Format:
The program should prompt the user to enter the following:
• Length of the room (a floating-point number)
• Width of the room (a floating-point number)
• Height of the room (a floating-point number)

2024-2028-CSD-B
Output Format:
The program should output the surface area of the room, rounded to two decimal places.
Source Code:

surfaceArea.c
#include<stdio.h>

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


void main()
{
float length,width,height;
scanf("%f%f%f",&length,&width,&height);
float surfacearea;
surfacearea=2*(length*width+length*height+width*height);
printf("%.2f",surfacearea);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
30
40
60
10800.00
32
70
55

15700.00
User Output
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 12
Exp. Name: Convert given time to Date: 2024-10-
S.No: 8

Page No: 13
minutes 03

Aim:
You need to convert a given time specified in hours and minutes to minutes only. Write a

ID: 247Y1A6790
C program that prompts the user to input the time in hours and minutes and then
displays the total time converted to minutes.

Input Format:
• The program should prompt the user to enter the hours and minutes as space-
separated integers

Output Format:
• The program should output the total time converted to minutes.

2024-2028-CSD-B
Source Code:

convertToMinutes.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int hours,min,tm;
scanf("%d%d",&hours,&min);
tm=(hours*60)+min;
printf("%d",tm);

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1 20
80

Test Case - 2

User Output
150
2 30

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 14
Date: 2024-10-
S.No: 9 Exp. Name: Coin Distribution

Page No: 15
03

Aim:
You have a money pouch containing a certain total amount of money. The pouch

ID: 247Y1A6790
contains an equal number of 25 paise coins, 50 paise coins, and 1 rupee coins. Write a C
program to determine how many of each type of coin are present if the total amount of
money in the pouch is given.

Input Format:
• The program should prompt the user to enter the total amount of money in the
pouch (in rupees).

Output Format:
The program should output the following in separate lines:
• The number of 25 paise coins.

2024-2028-CSD-B
• The number of 50 paise coins.
• The number of 1 rupee coins.

Note:
• 1 rupee = 2 * 50 paise coins
• 1 rupee = 4 * 25 paise coins
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


moneyClassification.c
#include<stdio.h>
void main()
{
int tm,t;
float tc;
scanf("%d",&tm);
tc=0.25+0.50+1.0;
t=tm/tc;
printf("%d\n",t);
printf("%d\n",t);
printf("%d\n",t);
}

Execution Results - All test cases have succeeded!


Test Case - 1
800
800
800
400
400
400
700

1400
User Output
User Output

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 16
Date: 2024-10-
S.No: 10 Exp. Name: Velocity Calculation

Page No: 17
13

Aim:
Write a C program to calculate the final velocity of an object based on its initial velocity,

ID: 247Y1A6790
acceleration, and time. Use the following formula to calculate the final velocity: Velocity
= Initial Velocity + (Acceleration * Time).

Input Format:
The program should prompt the user to input :
• Initial Velocity (in meters per second)
• Acceleration (in meters per second squared)
• Time (in seconds) on separate lines

Output Format:
The program should display the final velocity (in meters per second) calculated using the

2024-2028-CSD-B
formula.

Source Code:

velocityCalculator.c
#include<stdio.h>

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<math.h>
void main()
{
float iv,acc,time,fv;
scanf("%f%f%f",&iv,&acc,&time);
fv=iv+(acc*time);
printf("%.2f m/s\n",fv);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
10
2
5
20.00 m/s
0

10
9.8

98.00 m/s
User Output
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 18
Exp. Name: Area of Triangle using Date: 2024-10-
S.No: 11

Page No: 19
Heron's Formula 08

Aim:
Write a C program to calculate the area of a triangle given the lengths of its three sides.

ID: 247Y1A6790
Use Heron's formula to compute the area: Area = √(s * (s - Side1) * (s - Side2) * (s -
Side3)), where s = (Side1 + Side2 + Side3) / 2.

Input Format:
The program should prompt the user to input:
• Length of Side1 (in floating-point numbers)
• Length of Side2 (in floating-point numbers)
• Length of Side3 (in floating-point numbers)

Output Format:
The program should display the area of the triangle (rounded off to two decimal places)

2024-2028-CSD-B
calculated using Heron's formula.
Source Code:

areaOfTriangle.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


void main()
{
float side1,side2,side3;
scanf("%f%f%f",&side1,&side2,&side3);
float s=(side1+side2+side3)/2;
float area=sqrt(s*(s-side1)*(s-side2)*(s-side3));
printf("%.2f",area);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
12
13
30.00
8
6

10
24.00
User Output
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 20
Exp. Name: Salary Calculation of Date: 2024-10-
S.No: 12

Page No: 21
Employee 08

Aim:
ABC Company needs to calculate the monthly salary for its employees based on several

ID: 247Y1A6790
components. The salary calculation follows these rules:
1. Basic Pay: A fixed amount given to each employee.
2. DA (Dearness Allowance): 20% of the Basic Pay.
3. HRA (House Rent Allowance): 10% of the Basic Pay.
4. Gross Salary: Sum of Basic Pay, DA, and HRA.
5. Net Salary: Gross Salary minus deductions for taxes and provident fund.
Write a C program to compute the Gross Salary and Net Salary of an employee based on
the following input values:
• Basic Pay
• Deductions for Taxes
• Deductions for Provident Fund

2024-2028-CSD-B
The program should output the Gross Salary and Net Salary.

Input Format
A single line containing three space-separated floating-point numbers:
• Basic Pay
• Deductions for Taxes
• Deductions for Provident Fund

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Output Format
Two lines of output:
• The first line should display the Gross Salary.
• The second line should display the Net Salary.
Source Code:

salaryCalculation.c
#include<stdio.h>
void main()
{
float basic,dt,dp;
scanf("%f%f%f",&basic,&dt,&dp);
float da=0.20*basic;
float hra=0.10*basic;
float gross=basic+da+hra;
printf("%.2f\n",gross);
float net=gross-(dt+dp);
printf("%.2f\n",net);
}
Execution Results - All test cases have succeeded!

Page No: 22
Test Case - 1

User Output
30000 1000 500

ID: 247Y1A6790
39000.00
37500.00

Test Case - 2

User Output
45000 2500 1000
58500.00
55000.00

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Date: 2024-10-
S.No: 13 Exp. Name: Average of Three Values

Page No: 23
13

Aim:
Raju's father caught him tinkering with the computer and reminded him to focus on his

ID: 247Y1A6790
homework first. The math question assigned to him involves calculating the average of
three integers. Since he's unsure how to proceed, he seeks your assistance. Write a C
program to compute the average of three integers. The program should prompt the user
to enter these integers, calculate their average, and display the result formatted to two
decimal places.

Input/Output Format:

Input: Three integers entered by the user.


Output: The average of the three integers displayed with two decimal places.

2024-2028-CSD-B
Requirements:
• Use integer variables to store the input values.
• Perform type conversion as necessary to compute the average as a floating-point
number.
• Print the result formatted to two decimal places using printf.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Average.c

#include<stdio.h>
void main()
{
int a,b,c;
float avg;
scanf("%d%d%d",&a,&b,&c);
avg=(float)(a+b+c)/3;
printf("%.2f\n",avg);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
10 20 30
20.00
0.00
5.00
555

25.00

-10 0 10
15 25 35

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 24
Date: 2024-10-
S.No: 14 Exp. Name: Temperature Conversion

Page No: 25
13

Aim:
You are tasked with creating a program to convert temperatures between Celsius and

ID: 247Y1A6790
Fahrenheit. Your program should handle user input for temperature values and provide
accurate conversions, allowing seamless conversion between Celsius and Fahrenheit for
your weather forecasting needs.

Input Format:
The program first prompts for a temperature in for conversion.

Output Format:
Print the conversion of the temperature to Fahrenheit formatted to two decimals.
Print the conversion of the same temperature to Celsius formatted to two decimals.
Source Code:

2024-2028-CSD-B
temperature.c
#include<stdio.h>
int main() {
float t,c,f;
printf("Enter temperature: ");

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%f",&t);
f=t*1.8+32;
printf("%.2f Celsius is equal to %.2f Fahrenheit\n",t,f);
c=(t-32)*5/9;
printf("%.2f Fahrenheit is equal to %.2f Celsius\n",t,c);

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter temperature:
35
35.00 Celsius is equal to 95.00 Fahrenheit
35.00 Fahrenheit is equal to 1.67 Celsius
Test Case - 2

Page No: 26
User Output
Enter temperature:
45.5
45.50 Celsius is equal to 113.90 Fahrenheit

ID: 247Y1A6790
45.50 Fahrenheit is equal to 7.50 Celsius

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Date: 2024-10-
S.No: 15 Exp. Name: The Tall Men Next Door

Page No: 27
13

Aim:
XYZ Company has four brothers living next door, each with a different height. The

ID: 247Y1A6790
company knows the following details:
6. The average height of the four brothers is provided by the user.
7. The difference in height between the first and second brothers, and the second
and third brothers is 2 inches each.
8. The difference in height between the third and the fourth brother is 6 inches.
Write a C program that takes the average height of the four brothers as input and
calculates their individual heights based on the given conditions. The program should
output: The height of each of the four brothers.

Input Format:
• A single floating-point number representing the average height of the four

2024-2028-CSD-B
brothers.

Output Format:
• Four lines of output displaying the height of each brother.
Source Code:

findHeights.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
void main()
{
float avgheight;
scanf("%f",&avgheight);
float noofbrothers=4;
float totalheight=avgheight*4;
float x=(totalheight-16)/4;
int h1=x;
int h2=x+2;
int h3=x+4;
int h4=x+10;
printf("%d\n",h1);
printf("%d\n",h2);
printf("%d\n",h3);
printf("%d\n",h4);
}

Execution Results - All test cases have succeeded!


80
74
72
70
74
68
66
64
68

74.0
User Output
User Output

Test Case - 2
Test Case - 1

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 28
Date: 2024-10-
S.No: 16 Exp. Name: Driving through the country

Page No: 29
13

Aim:
You have decided to travel through the country, increasing your travel distance each day.

ID: 247Y1A6790
The journey follows these rules:
9. On the first day, you traveled a certain number of miles.
10. On the last day, you traveled a different number of miles.
11. Each day, you increased your travel distance by a fixed number of miles.
Write a C program that calculates the following:
12. The total number of days traveled.
13. The total distance traveled over the entire journey.

Input Format:
• An integer representing the distance traveled on the first day (in miles).
• An integer representing the distance traveled on the last day (in miles).

2024-2028-CSD-B
• An integer representing the daily increment in distance (in miles).

Output Format:
• The number of days traveled.
• The total distance traveled.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


calculateDays.c
#include<stdio.h>
void main()
{
int dx,dy,dz,n,td;
scanf("%d%d%d",&dx,&dy,&dz);
n=(dy-dx)/dz+1;
td=(n/2.0)*(dx+dy);
printf("%d\n",n);
printf("%d\n",td);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
9
9

5
3

50
10
29

270
153

User Output
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 30
Date: 2024-10-
S.No: 17 Exp. Name: Monitor water level

Page No: 31
13

Aim:
There is a beautiful pond in a park, filled with clear water. The park management wants to

ID: 247Y1A6790
monitor the water level in the pond regularly to ensure it remains at an optimal level.
They have asked you to create a C program to help them with this task. Develop a
program to monitor the water level in the pond and notify the park management if it falls
below a certain threshold.

Input Format
• Current Water Level: A floating-point number representing the current water level
in meters.
• Threshold Level: A floating-point number representing the threshold water level in
meters.

2024-2028-CSD-B
Output Format
• If the water level is below the threshold level print the message "The water level
has fallen below the threshold level"
• Otherwise, print "The water level is at an acceptable level"

Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


waterLevel.c
#include<stdio.h>
void main()
{
float cwl;
scanf("%f",&cwl);
float tl;
scanf("%f",&tl);
if(cwl<tl)
printf("The water level has fallen below the threshold
level\n");
else
printf("The water level is at an acceptable level\n");
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 32
1.5 2
The water level has fallen below the threshold level

Test Case - 2

ID: 247Y1A6790
User Output
2.5 2
The water level is at an acceptable level

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Date: 2024-10-
S.No: 18 Exp. Name: Maximum submissions

Page No: 33
13

Aim:
You are participating in a programming contest where you can make one submission

ID: 247Y1A6790
every 45 seconds. The contest lasts for a given number of minutes. Develop a C program
to determine the maximum number of submissions you can make during the contest.

Input Format:
• An integer representing the duration of the contest in minutes.

Output Format:
• An integer representing the maximum number of submissions possible during the
contest.
Source Code:

2024-2028-CSD-B
maxSubmissions.c

#include<stdio.h>
void main()
{
int cd,sub,sec;
scanf("%d",&cd);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int submission=45;
sec=60;
int totaldurationinseconds=cd*sec;
int maxsubmisssions=totaldurationinseconds/submission;
printf("%d\n",maxsubmisssions+1);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
3

Test Case - 2

User Output
7
5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 34
Date: 2024-10-
S.No: 19 Exp. Name: Largest Number

Page No: 35
13

Aim:
Michael wants to find the largest number among a set of given numbers. Help Michael to

ID: 247Y1A6790
write a C program to determine the largest number from the given inputs.

Input Format:
• An integer representing the number of elements in the set.
• Followed by the integers representing the elements in the set.

Output Format:
• The largest number among the given inputs

Source Code:

2024-2028-CSD-B
largestNum.c

#include<stdio.h>
int main()
{
int nes;
scanf("%d",&nes);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


if(nes<=0){
printf("invalid nes.\n");
return 1;}
int largest;
scanf("%d",&largest);
for (int i=2;i<=nes;i++){
int current;
scanf("%d",&current);
if (current>largest){
largest=current;}
}
printf("%d\n",largest);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
2
3

66
44

66
45
21
44
29

User Output
User Output

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 36
Date: 2024-10-
S.No: 20 Exp. Name: Cost of the painting

Page No: 37
13

Aim:
A construction worker needs to paint the exterior walls of a rectangular building. The

ID: 247Y1A6790
dimensions of the walls are L meters in length, H meters in height, and W meters in width.
If the cost of painting is Rs. 20 per square meter, what will be the total cost of painting
the walls? Write a C program to implement the given

Input Format
• A floating-point number representing the length of the building in meters.
• A floating-point number representing the height of the building in meters.
• A floating-point number representing the width of the building in meters.

Output Format
• A floating-point number representing the total cost of painting the exterior walls,

2024-2028-CSD-B
formatted to two decimal places.

Hint: Use the surface area of the exterior walls to calculate the total painting cost.
Source Code:

costOfPainting.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main()
{
float l,h,w,a,c,tc;
scanf("%f%f%f",&l,&h,&w);
c=20.0;
a=2*(l*h+w*h);//2*(l*h+w*h)
tc=a*c;
printf("%.2f\n",tc);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
10.0
5.0
6.0
5.0
5.0
20.0

5000.00
3200.00

User Output
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 38
Exp. Name: Finding the number of liters Date: 2024-10-
S.No: 21

Page No: 39
of ice cream left 13

Aim:
An ice cream vendor brings i liter of ice cream to a fair. Each cone requires 0.25 liters of

ID: 247Y1A6790
ice cream. If the vendor sells 80 cones, Develop a C program to find the number of liters
of ice cream left with the vendor.

Input Format:
• A floating-point number representing the total amount of ice cream brought by
the vendor (in liters).

Output Format:
• A floating-point number representing the amount of ice cream left with the vendor
(in liters), rounded to two decimal places.
Source Code:

2024-2028-CSD-B
icecreamLeft.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


tic,cones,icc,uic,ric;
scanf("%f",&tic);
icc=0.25;
cones=80;
uic=cones*icc;
ric=tic-uic;
printf("%.2f\n",ric);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
100
80.00

Test Case - 2
60
40.00
User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 40
Exp. Name: Calculating the total Date: 2024-10-
S.No: 22

Page No: 41
number of guests 13

Aim:
Amanda is planning a party and wants to determine the total number of guests

ID: 247Y1A6790
attending. Assist Amanda by writing a C program to calculate the total number of guests
based on the number of adults and children invited.

Input Format:
• An integer representing the number of adults invited to the party.
• An integer representing the number of children invited to the party.

Output Format:
• An integer representing the total number of guests attending the party.
Source Code:

2024-2028-CSD-B
guestsCalculation.c
#include<stdio.h>
int main()
{
int a,c,g;
scanf("%d%d",&a,&c);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


g=a+c;
printf("%d\n",g);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
13
18

Test Case - 2

User Output
4
24
20

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 42
Exp. Name: Calculate and display the
Date: 2024-10-

Page No: 43
S.No: 23 maturity amount using the Simple
13
Interest.

Aim:

ID: 247Y1A6790
You are working as a financial analyst at a bank. As part of your job, you need to calculate
the maturity amount for fixed deposits (FD) based on the principal amount, interest rate,
and duration. Write a C program that takes the principal amount, interest rate, and
duration (in years) as input from the user.

Calculate and display the maturity amount using the simple interest formula: Maturity
Amount = Principal + (Principal * Interest Rate * Duration)/100.

Input Format:
• Input the principal amount, interest rate as float and duration separated by a space

2024-2028-CSD-B
Constraints:
• 1 <= amount <= 1000000
• 0 <= interest rate <= 10
• 1 <= duration <= 20

Output Format:
• Display the maturity amount upto two decimal points

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

MaturityAmount.c

#include<stdio.h>
int main()
{
float pa,ir,ma;
float d;
scanf("%f%f%f",&pa,&ir,&d);
ma=pa+(pa*ir*d)/100;
printf("%.2f",ma);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
25000 1.2 2
25600.00

Page No: 44
Test Case - 2

User Output

ID: 247Y1A6790
5000 5 2
5500.00

Test Case - 3

User Output
1000 7.5 3
1225.00

2024-2028-CSD-B
Test Case - 4

User Output
2500 3.2 4.5
2860.00

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
8000 2 1.5
8240.00
Exp. Name: Calculate the area of a Date: 2024-10-
S.No: 24

Page No: 45
rectangle. 13

Aim:
Jenny, a budding mathematician, was studying the concept of area and perimeter. She

ID: 247Y1A6790
was given a rectangular garden with a known length and width. Jenny wondered if she
could find the area without knowing the width. Can you help Jenny derive a formula to
calculate the area of a rectangle using only the length and perimeter?

Input Format:
• Input the length and perimeter of rectangle of type double separated with a space

Constraints:
• 1 <= length <= 100000
• 1 <= perimeter <= 1000000

2024-2028-CSD-B
Output Format:
• Display Area of the Rectangle rounded upto two decimals

Hint : Use Formula as perimeter


length 2
× ( ) − (length)
2

Source Code:

Area.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main()
{
int l;
int p;
float a;
scanf("%d%d",&l,&p);
a=l*((p/2.0)-l);
printf("%.2f\n",a);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5 18
Test Case - 2

Page No: 46
User Output
10 40
100.00

ID: 247Y1A6790
Test Case - 3

User Output
5 50
100.00

Test Case - 4

2024-2028-CSD-B
User Output
8 30
56.00

Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
3 18
18.00
Exp. Name: Program on Pythagorean Date: 2024-10-
S.No: 25

Page No: 47
theorem. 13

Aim:
Write a C program to calculate the hypotenuse of a right-angled triangle given the

ID: 247Y1A6790
lengths of its two perpendicular sides. The program should prompt the user to enter the
lengths and then display the result.

Formula:
Hypotenuse² = Side1² + Side2²

Input Format:
Enter two floating-point numbers for side1 and side2.

Constraints:
1 ≤ side1, side2 ≤ 100000

2024-2028-CSD-B
Output Format:
Display the hypotenuse as a float rounded to two decimal places.
Source Code:

Triangle.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
#include<math.h>
int main()
{
float s1,s2,hyp;
scanf("%f%f",&s1,&s2);
hyp=sqrt((s1*s1)+(s2*s2));
printf("%.2f\n",hyp);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
34
5.00
11

5 12
1.41

13.00
12.10
7.5 9.5

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 48
Exp. Name: Sum of first n natural Date: 2024-10-
S.No: 26

Page No: 49
numbers 13

Aim:
Once upon a time, there was a mathematician named Alex. Alex loved solving

ID: 247Y1A6790
mathematical problems and puzzles. One day, Alex came across an ancient scroll that
contained a secret formula to calculate the sum of the first n natural numbers. The scroll
mentioned that by using the formula, one could find the sum of any given number of
natural numbers without having to manually add them up. Alex was intrigued and
decided to test the formula. Can you help Alex implement a C program that uses the
formula to calculate the sum of the first n natural numbers?

Hint: sum = (n * (n + 1)) / 2

Input Format:
• Input an integer n.

2024-2028-CSD-B
Constraints:
• 1 <= n <= 105

Output Format:
• Display the sum of the first n natural numbers.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Sum.c

#include<stdio.h>
int main()
{
int n,sum;
scanf("%d",&n);
sum=(n*(n+1))/2;
printf("%d\n",sum);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
15
Test Case - 2

Page No: 50
User Output
1
1

ID: 247Y1A6790
Test Case - 3

User Output
20
210

Test Case - 4

2024-2028-CSD-B
User Output
10
55

Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
100
5050
Exp. Name: Calculate Slope of two Date: 2024-10-
S.No: 27

Page No: 51
points 13

Aim:
Once upon a time in a small town, there were two friends, Kavi and Jei, who were

ID: 247Y1A6790
fascinated by the concept of slopes in mathematics. They loved exploring the hills and
valleys around their town and wondered how they could calculate the slope of any given
landscape. One sunny day, while hiking up a hill, Kavi and Jei discovered an ancient map
that had the secret to finding the slope of a line between two points. The map indicated
that by using the coordinates of two points, they could determine the slope of the line
connecting them. Excited about their discovery, Kavi and Jei decided to create a C
program that could calculate the slope for any two points. They wanted to share their
program with others so that everyone could explore the slopes of various landscapes.
Help Kavi and Jei to implement the program.

Hint: slope = (y2 - y1) / (x2 - x1)

2024-2028-CSD-B
Input Format
• Input the coordinates of two points: x1, y1, x2, y2 of type float separated by space.

Constraints:
• 1 <= x1, y1, x2, y2 <= 106

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Output Format:
• Display the slope value rounded upto two decimals
Source Code:

Slope.c
#include<stdio.h>
int main()
{
float x1,y1,x2,y2,slope;
scanf("%f%f%f%f",&x1,&y1,&x2,&y2);
slope=(y2-y1)/(x2-x1);
printf("%.2f\n",slope);
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 52
6 3 18 36
2.75

Test Case - 2

ID: 247Y1A6790
User Output
2.56 2.65 5.5 6.7
1.38

Test Case - 3

User Output
14.5 13.7 16.4 17.8

2024-2028-CSD-B
2.16

Test Case - 4

User Output
23.45 25.6 22.4 23.45

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


2.05
Exp. Name: Calculate distance between Date: 2024-10-
S.No: 28

Page No: 53
two points. 13

Aim:
Ravi and Kavi are on an exciting treasure hunt adventure, following a map with hidden

ID: 247Y1A6790
treasures located at different coordinates. They want to calculate the distance between
two treasures to determine how far apart they are.

Help them to write a C program that prompts the user to enter the coordinates of two
treasures: Treasure A and Treasure B and calculate the distance between them. The
coordinates should be in the form (x, y).

Hint: distance = sqrt ((x


2 2
2 − x1) + (y2 − y1) )

Input Format:
• Input x1 and y1 in first line

2024-2028-CSD-B
• Input x2 and y2 in second line

Constraints:
•1≤x 1 , y1 , x2 , y2 ≤ 10
5

Output Format:
• Display the distance between two points.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

distance.c
#include<stdio.h>
#include<math.h>
int main()
{
float x1,y1;
float x2,y2;
float d;
scanf("%f%f%f%f",&x1,&y1,&x2,&y2);
d=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
printf("%.2f\n",d);
}

Execution Results - All test cases have succeeded!


User Output

Page No: 54
22
44
2.83

ID: 247Y1A6790
Test Case - 2

User Output
3.5 1.0
1.0 3.5
3.54

Test Case - 3

2024-2028-CSD-B
User Output
-3.0 -4.0
3.0 4
10.00

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
10.0 10
00
14.14

Test Case - 5

User Output
-6 -4
-2 -4
4.00
Date: 2024-10-
S.No: 29 Exp. Name: Coconut Shot Calculator

Page No: 55
13

Aim:
Imagine a scenario where there is a coconut tree with multiple coconuts hanging from it.

ID: 247Y1A6790
There is a person standing at a distance of D meters away from the tree. The coconuts are
positioned at a height of H meters from the ground. Could you please help him to write a
C program that calculates the angle at which the person should aim in order to hit the
coconuts?

Hint: You can use the inverse tangent function (atan() in C) to determine the angle based
on the ratio of the height of the coconuts to the distance from the tree.

Input Format:
First line contains an integer D representing the distance from the person to the tree
Second line contains an integer H representing the height of the tree

2024-2028-CSD-B
Constraints:
1 <= D, H <= 105

Output Format:
Return the angle in float format

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Note: Round off the result to two decimal points
Source Code:

angleToAim.c
#include<stdio.h>
#include<math.h>
int main()
{
float d,h,a;
scanf("%f%f",&d,&h);
a=atan(h/d);
a=a*(180.0/M_PI);
printf("%.2f\n",a);
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 56
10
4
21.80

ID: 247Y1A6790
Test Case - 2

User Output
10
15
56.31

Test Case - 3

2024-2028-CSD-B
User Output
70.1
15.2
12.23

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
15.5
70.5
77.60

Test Case - 5

User Output
20.0
8.0
21.80
Exp. Name: A Treasure Hunter's Date: 2024-10-
S.No: 30

Page No: 57
Dilemma 13

Aim:
In a faraway kingdom, two treasure hunters named Alex and Bella embarked on a daring

ID: 247Y1A6790
quest to find valuable treasures. While exploring a mysterious cave, they stumbled upon
two treasure chests, each containing a unique gemstone. Curiosity took over, and they
decided to swap the gemstones inside the chests. However, a magical enchantment
prevented them from directly swapping the gemstones. To fulfill their quest and restore
the treasures to their rightful chests, Alex and Bella realized they could use a third
variable and arithmetic operations. Can you help them by writing a C program that takes
the values of the gemstones as input, and swap their values.

Input Format:
First line contains an integer a, representing the value of gemstone 1
Second line contains an integer b, representing the value of gemstone 2

2024-2028-CSD-B
Constraints:
1 <= a, b <= 104

Output Format:
Return the a, b values after swapping, separated by space.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


gemStoneSwapper.c

#include<stdio.h>
int main()
{
int a,b,s;
scanf("%d%d",&a,&b);
s=a;
a=b;
b=s;
printf("%d %d",a,b);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
6
5

65
15
65
23
20
10
6 5

65 15
65 23
20 10

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 58
Exp. Name: Calculating Cylinder Surface Date: 2024-10-
S.No: 31

Page No: 59
Area 13

Aim:
Emily, a young architect, was working on designing a cylindrical water tank for a new

ID: 247Y1A6790
building. As she was finalizing the plans, she needed to calculate the surface area of the
cylinder to determine the amount of material required for its construction. However, she
was unsure of the exact formula and the steps involved in the calculation. Can you help
Emily by writing a C program that assists her in calculating the surface area of a cylinder?

Hint: Surface Area = 2πr² + 2πrh

Input Format:
• The first line contains a float value representing the radius of the cylinder.
• The second line contains a float value representing the height of the cylinder.

2024-2028-CSD-B
Output Format:
• A single float value with two decimal points representing the surface area of the
cylinder.

Constraints:
1 <= r, h <= 105

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Note:
• Round off the final result to two decimal points.
• Use M_PI from the math library for the "π" value
Source Code:

surfaceArea.c

#include<stdio.h>
#include<math.h>
int main()
{
float r,h,sa;
scanf("%f%f",&r,&h);
sa=2*M_PI*r*r+2*M_PI*r*h;
printf("%.2f",sa);
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 60
User Output
2.68
8.1

ID: 247Y1A6790
181.52

Test Case - 2

User Output
16.2
7.21
2382.85

2024-2028-CSD-B
Test Case - 3

User Output
10.0
10.0
1256.64

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
1.5
2.5
37.70

Test Case - 5

User Output
15.62
9.5
2465.36
Date: 2024-10-
S.No: 32 Exp. Name: Polygon Area Calculator

Page No: 61
13

Aim:
Hemanth is an architect who wants to design a garden with a beautiful polygon-shaped

ID: 247Y1A6790
fountain at its canter. He needs to calculate the area of the polygon so that he can
determine the appropriate size for the garden. Help Hemanth by writing a C program that
calculates the area of a regular polygon when given the number of sides, N, and the
length of each side, L. UseM_PI as the constant for PI.

Hint: Area = (N * L * L) / (4 * tan(M_PI / N))

Input Format:
• First line of input contains an integer N representing the sides no of sides of the
polygon.
• Second line of input contains a floating value L representing the length of each

2024-2028-CSD-B
side.

Constraints:
• 1 <= N <= 103
• 1 <= L <= 105

Output Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The output is a float value represents the area of regular polygon.

Note: Round off the output to two decimal points.


Source Code:

areaOfFountain.c

#include<stdio.h>
#include<math.h>
int main()
{
int n;
float l,a;
scanf("%d%f",&n,&l);
a=(n*l*l)/(4*tan(M_PI/n));
printf("%.2f",a);
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 62
User Output
4
5

ID: 247Y1A6790
25.00

Test Case - 2

User Output
10
2.5
48.09

2024-2028-CSD-B
Test Case - 3

User Output
20
2.3
167.00

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
20
10.0
3156.88

Test Case - 5

User Output
10
15.5
1848.53
Exp. Name: Calculating Cone Surface Date: 2024-10-
S.No: 33

Page No: 63
Area 13

Aim:
Prathima loves ice cream cones and wants to decorate the surface of her favorite ice

ID: 247Y1A6790
cream cone with colorful stickers. To know how many stickers she needs, she wants to
calculate the surface area of the cone. Help Prathima by writing a C program that
calculates the surface area of a cone when given the radius of the base, r, and the slant
height, L. Use π as 3.14.

Hint: Surface Area = π * r * (r + L))

Input Format:
First line of input contains an integer r representing the radius of base of the cone
Second line of input contains an integer L representing the slant height of the cone

2024-2028-CSD-B
Constraints:
1 <= r, L <= 105

Output Format:
Print the surface area of the cone

Note: Round off the final result to two decimal points.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

surfaceAreaOfCone.c

#include<stdio.h>
void main()
{
double r,l,sa;
scanf("%lf%lf",&r,&l);
sa=3.14*r*(r+l);
printf("%.2lf",sa);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2.65
9
96.94

Page No: 64
Test Case - 2

User Output

ID: 247Y1A6790
9
2.3
319.34

Test Case - 3

User Output
3.54

2024-2028-CSD-B
4.5
89.37

Test Case - 4

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


5.6
8.4
246.18

Test Case - 5

User Output
6.5
10.0
336.76
Date: 2024-10-
S.No: 34 Exp. Name: A Tale of Short and Tall

Page No: 65
13

Aim:
A short man takes n steps to a tall man's m steps. They both start out on the left foot.

ID: 247Y1A6790
How many steps do they have to take before they are both stepping out on the right foot
together?

Input Format:
First line of input contains an integer n representing the steps taken by short man
Second line of input contains an integer m representing the steps taken by tall man

Output Format:
Print the total no of steps that the short man and the tall man take so that they both can
step out on the right foot together.
Source Code:

2024-2028-CSD-B
noOfSteps.c

#include<stdio.h>
int gcd(int a,int b){
while (b!=0){
int temp=b;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


b=a%b;
a=temp;
}
return a;
}
int lcm(int a,int b){
return(a*b)/gcd(a,b);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int ts=lcm(n,m);
printf("%d",ts);
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 66
3
2
6

ID: 247Y1A6790
Test Case - 2

User Output
6
4
12

Test Case - 3

2024-2028-CSD-B
User Output
1
1
1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
16
5
80

Test Case - 5

User Output
15
3
15
Date: 2024-10-
S.No: 35 Exp. Name: Dice Game Assessment

Page No: 67
25

Aim:
Chef and Chefina are playing with dice. In one turn, both of them roll their dice at once.

ID: 247Y1A6790
They consider a turn to be good if the sum of the numbers on their dice is greater than 6.

Given that in a particular turn, Chef and Chefina got X and Y on their respective dice,
find whether the turn was good.

Input Format:
• Input contains two space-separated integersX and Y - the numbers Chef and
Chefina got on their respective dice.

Constraints:
• 1 ≤ X, Y ≤ 100

2024-2028-CSD-B
Output format:
• Output a new line, YES, if the turn was good and NO otherwise.
Source Code:

dice.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main()
{
int chef,chefina;
scanf("%d%d",&chef,&chefina);
int totalsum=chef+chefina;
if(totalsum>6){
printf("YES\n");
}else{
printf("NO\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
14
NO
NO

26
42
34

YES
YES

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 68
Date: 2024-10-
S.No: 36 Exp. Name: Masterchef finals

Page No: 69
25

Aim:
Chef has been working hard to compete in MasterChef. He is ranked X out of all

ID: 247Y1A6790
contestants. However, only 10 contestants would be selected for the finals.

Check whether Chef made it to the top 10 or not.

Input Format:
• Input contains one integerX - the current rank of Chef.

Constraints:
•1≤X ≤ 100

Output format:

2024-2028-CSD-B
• Output a new line, YES, if Chef made it to the top10 and NO otherwise.
Source Code:

chefRank.c

#include<stdio.h>
int main()

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


{
int x;
scanf("%d",&x);
if(x<=10){
printf("YES\n");
}else{
printf("NO\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
15
NO
1

NO
50
10

YES
YES

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 70
Date: 2024-10-
S.No: 37 Exp. Name: Battery Health

Page No: 71
25

Aim:
Apple considers any iPhone with a battery health of 80 or above, to be in optimal

ID: 247Y1A6790
condition.

Given that your iPhone has X battery health, find whether it is in optimal condition or
not.

Input Format:
• Input contains an integerX - the battery health.

Constraints:
•0≤X ≤ 100

2024-2028-CSD-B
Output format:
• Output a new line, YES, if the battery is in optimal condition and NO otherwise.
Source Code:

battery.c

#include<stdio.h>

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int main()
{
int x;
scanf("%d",&x);
if(x>=80){
printf("YES\n");
}else{
printf("NO\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
97
YES
NO
NO

10
80
42

YES

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 72
Date: 2024-10-
S.No: 38 Exp. Name: Tom and Jerry Chase.

Page No: 73
25

Aim:
In a classic chase, Tom is running after Jerry as Jerry has eaten Tom's favourite food. Jerry

ID: 247Y1A6790
is running at a speed of X metres per second while Tom is chasing him at a speed of Y
metres per second. Determine whether Tom will be able to catch Jerry. Note that initially,
Jerry is not in the same position as Tom.

Input Format:
• The input contains two space-separated integersX and Y - the speeds of Jerry
and Tom respectively.

Constraints:
• 1 ≤ X, Y ≤ 10

2024-2028-CSD-B
Output Format:
• Return YES, if Tom will be able to catch Jerry. Otherwise, NO.
Source Code:

chase.c

#include<stdio.h>

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int main()
{
int jerry,tom;
scanf("%d%d",&jerry,&tom);
if(tom>jerry){
printf("YES\n");
}else{
printf("NO\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
23
YES
NO
NO

35
11
41

YES
User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 74
Exp. Name: Check whether Chef can
Date: 2024-10-

Page No: 75
S.No: 39 complete the entire textbook within a
25
given number of days

Aim:

ID: 247Y1A6790
Chef has started studying for the upcoming test. The textbook has N pages in total. Chef
wants to read at most X pages a day for Y days. Find out whether it is possible for Chef
to complete the whole book.

Input Format:
• The first line of input contains a single integer N , denoting the number of pages.
• The second line of input contains two space-separated integers X and Y ,
denoting the number of pages Chef can read in a day, and the number of days.

Constraints:
•1≤N ≤ 100

2024-2028-CSD-B
• 1 ≤ X, Y ≤ 10

Output Format:
• Return YES, if Chef can complete the whole book in the given time, and NO
otherwise.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Pages.c

#include<stdio.h>
int main()
{
int n;
int x,y;
scanf("%d%d%d",&n,&x,&y);
if(x*y>=n){
printf("YES\n");
}else{
printf("NO\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1
3
7
5

NO
NO
10

21
71
33
23

YES
YES

User Output
User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 76
Exp. Name: Chef's Race to the F1 Date: 2024-10-
S.No: 40

Page No: 77
Tournament 25

Aim:
Chef has finally got the chance of his lifetime to drive in the F1 tournament. But, there is

ID: 247Y1A6790
one problem. Chef did not know about the 107% rule and now he is worried whether he
will be allowed to race in the main event or not.

Given the fastest finish time as X seconds and Chef's finish time as Y seconds, determine
whether Chef will be allowed to race in the main event or not.

Note that, Chef will only be allowed to race if his finish time is within 107% of the fastest
finish time.

Input Format:
First line of input contains an integer X representing the fastest finish time

2024-2028-CSD-B
Second line of input contains an integer Y representing the Chef's finish time

Output Format:
Print Yes if Chef will be allowed to race in the main event, else printNo

Constraints:
1 <= X <= Y <= 200

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Example:
Input:
X: 1
Y: 2

Output:
No

Explanation: The fastest car finished in1 second. Thus, Chef should have finished on or
before1.07 seconds to ensure qualification but he finished in2 seconds. Hence, Chef will
not be allowed to race in the main event.
Source Code:

chefF1Tournament.c
#include<stdio.h>

Page No: 78
int main()
{
int x;
int y;
scanf("%d%d",&x,&y);

ID: 247Y1A6790
if(y<=x*1.07){
printf("Yes\n");
}else{
printf("No\n");
}
}

Execution Results - All test cases have succeeded!

2024-2028-CSD-B
Test Case - 1

User Output
15
16
Yes

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 2

User Output
15
17
No

Test Case - 3

User Output
100
107
Yes

Test Case - 4
2
1
5

No
10

Yes

User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 79
Exp. Name: Can the Party Hall Fit Date: 2024-10-
S.No: 41

Page No: 80
Everyone 25

Aim:
Chef wants to host a party with a total of N people. However, the party hall has a capacity

ID: 247Y1A6790
of X people. Find whether Chef can host the party.

Input Format:
First line of input contains an integer N representing the no of people
Second line of input contains an integer X representing the capacity of hall

Output Format:
Print Yes, if Chef can host the party, otherwise print No

Constraints:
1 <= N, X <= 10000

2024-2028-CSD-B
Source Code:

PartyHallCapacity.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int n;
int x;
scanf("%d%d",&n,&x);
if(n>x){
printf("No\n");
}else{
printf("Yes\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
5
Yes
Test Case - 2

Page No: 81
User Output
6
6

ID: 247Y1A6790
Yes

Test Case - 3

User Output
10
9
No

2024-2028-CSD-B
Test Case - 4

User Output
100
105
Yes

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
4
3
No
Exp. Name: One More Episode or the Date: 2024-11-
S.No: 42

Page No: 82
Exam 07

Aim:
Chef has to attend an exam that starts in X minutes, but of course, watching shows takes

ID: 247Y1A6790
priority. Every episode of the show that Chef is watching, is 24 minutes long. If he starts
watching a new episode now, will he finish watching it strictly before the exam starts?

Input Format:
Single line of input contains an integer X representing the time left for the test to start

Output Format:
Print Yes if Chef watch a new episode before the start time of the test, else print No

Constraints:
1 <= X <= 100

2024-2028-CSD-B
Source Code:

EpisodeOrExam.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int time;
scanf("%d",&time);
if(time<=24){
printf("No\n");
}else{
printf("Yes\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
23
No

Test Case - 2
No
No

25
20
10
60

Yes
Yes

User Output
User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 83
Date: 2024-11-
S.No: 43 Exp. Name: Chef's Fare Choice

Page No: 84
07

Aim:
Chef has to travel to another place. For this, he can avail any one of two cab services.

ID: 247Y1A6790
• The first cab service charges X rupees.
• The second cab service charges Y rupees.
Chef wants to spend the minimum amount of money. Which cab service should Chef
take?

Input Format:
First line of input contains an integer X representing the price of first cab service
Second line of input contains an integer Y representing the price of second cab service

Output Format:
Print First if the first cab service charges are less or print Second if the second service

2024-2028-CSD-B
charges are less or print Any if the service charges of both the cabs is same.

Constraints:
1 <= X <= Y <= 500
Source Code:

minCabCost.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main()
{
int X;
int Y;
scanf("%d%d",&X,&Y);
if(X<Y)
{
printf("First\n");
}
else if(X==Y)
{
printf("Any\n");
}
else
{
printf("Second\n");
}
}
Execution Results - All test cases have succeeded!

Page No: 85
Test Case - 1

User Output
30

ID: 247Y1A6790
65
First

Test Case - 2

User Output
25
25
Any

2024-2028-CSD-B
Test Case - 3

User Output
50
12

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Second

Test Case - 4

User Output
10
20
First

Test Case - 5

User Output
20
10
Second
Date: 2024-11-
S.No: 44 Exp. Name: Chef's Instagram Filter

Page No: 86
07

Aim:
Chef categorizes an Instagram account as spam, if, the following count of the account is

ID: 247Y1A6790
more than 10 times the count of followers.

Given the following and follower count of an account as X and Y respectively, find
whether it is a spam account.

Input Format:
First line of input contains an integer X representing the following count
Second line of input contains an integer Y representing the followers count

Output Format:
Print Yes, if the account is spam and No otherwise

2024-2028-CSD-B
Constraints:
1 <= X, Y <= 100

Example:
Input:
Following count: 21

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Follower count: 2

Output:
Yes

Explanation: The followers count is given as 2 and the following count is given as 21
which is more than 10 times of the followers count. So the account is a spam account.
Source Code:

SpamOrNot.c
#include<stdio.h>

Page No: 87
int main()
{
int X;
int Y;
scanf("%d%d",&X,&Y);

ID: 247Y1A6790
if(X>10*Y){
printf("Yes\n");
}else{
printf("No\n");
}
}

Execution Results - All test cases have succeeded!

2024-2028-CSD-B
Test Case - 1

User Output
21
2
Yes

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 2

User Output
10
2
No

Test Case - 3

User Output
1
10
No

Test Case - 4
1

No
11

Yes

523
521
User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 88
Exp. Name: Chef's Remote Control Date: 2024-11-
S.No: 45

Page No: 89
Challenge 21

Aim:
Chef is watching TV. The current volume of the TV is X. Pressing the volume up button of

ID: 247Y1A6790
the TV remote increases the volume by 1 while pressing the volume down button
decreases the volume by 1. Chef wants to change the volume from X to Y. Find the
minimum number of button presses required to do so.

Input Format:
First line of input contains an integer X representing the initial volume
Second line of input contains an integer Y representing the final volume

Output Format:
Print the minimum number of times Chef has to press a button to change the volume
fromX toY.

2024-2028-CSD-B
Constraints:
1 <= X, Y <= 100
Source Code:

VolumeChange.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main()
{
int X;
int Y;
scanf("%d%d",&X,&Y);
int presses = X > Y ? X - Y : Y - X;
printf("%d\n",presses);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
50
54
4
Test Case - 2

Page No: 90
User Output
12
10

ID: 247Y1A6790
2

Test Case - 3

User Output
100
20
80

2024-2028-CSD-B
Test Case - 4

User Output
56
15
41

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
96
45
51
Date: 2024-11-
S.No: 46 Exp. Name: Connecting Towns

Page No: 91
21

Aim:
Cities on a map are connected by a number of roads. The number of roads between each

ID: 247Y1A6790
city is in an array and city 0 is the starting location. The number of roads from city 0 to
city 1 is the first value in the array, from city 1 to city 2 in the second, and so on.

How many paths are there from city 0 to the last city in the list, modulo 1234567?

Input Format:
First line of input contains an integer N representing the no of cities
Second line contains N - 1 space separated integers where ith integer denotes the no of
routes, Ni, from the city Ti to Ti+1

Output Format:

2024-2028-CSD-B
Print the total no of routes, modulo 1234567

Constraints:
2 < N <= 100
1 <= routes[i] <= 1000

Example:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Input:
3
13

Output:
3

Explanation: 1 route from T1 to T2, 3 routes from T2 to T3, hence only 3 routes.
Source Code:

connectingTowns.c
#include<stdio.h>

Page No: 92
#define MOD 1234567
int main() {
int N;
scanf("%d",&N);
int routes[N - 1];

ID: 247Y1A6790
for(int i = 0; i < N - 1; i++) {
scanf("%d",&routes[i]);
}
long long totalPaths = 1;
for(int i = 0; i < N - 1; i++) {
totalPaths = (totalPaths * routes[i]) % MOD;
}
printf("%lld\n",totalPaths);
return 0;
}

2024-2028-CSD-B
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3
13
3

Test Case - 2

User Output
4
222
8

Test Case - 3

User Output
4
213
6
1
3
5

24

11
1234

User Output
User Output

Test Case - 5
Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 93
Date: 2024-12-
S.No: 47 Exp. Name: Count the squares

Page No: 94
03

Aim:
Write a C program to determine the total number of squaresthat can be formed in a grid

ID: 247Y1A6790
of size M x N, where M and N are positive integers.

Input Format:
Single line of input contains two space separated integers representing M and N
respectively

Output Format:
Print the total no of squares present in the given M*N grid.

Constraints:
1 <= M, N <= 100

2024-2028-CSD-B
Source Code:

countingSquares.c

#include<stdio.h>
int main(){
int M,N;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%d%d",&M,&N);
int totalsquares = 0;
for (int k = 1; k <= M && k <=N; k++){
totalsquares += (M - k + 1) * (N - k + 1);
}
printf("%d\n",totalsquares);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
22
5

Test Case - 2
2
1
8

20

12
11
43
32

User Output
User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 95
Exp. Name: Sum of digits of a five digit Date: 2024-12-
S.No: 48

Page No: 96
number. 03

Aim:
Given the five-digit number, print the sum of its digits.

ID: 247Y1A6790
Input Format:
• Input contains a single five digit number n

Constraints:
• 1000 ≤ n ≤ 99999

Output Format:
• Return the sum of individual digits, If the input is valid (i.e., n has exactly 5 digits)
• Return "Invalid input", If the input is invalid (i.e., n does not have exactly 5 digits)
Source Code:

2024-2028-CSD-B
sum.c

#include<stdio.h>
int main(){
int n,sum=0,c=0,t;
scanf("%d",&n);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


t=n;
while(t!=0)
{
c=c+1;
t=t/10;
}
if(c==5)
{
while(n!=0)
{
sum=sum+n%10;
n=n/10;
}
printf("%d\n", sum);
} else {
printf("Invalid input\n");
}
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 97
Test Case - 1

User Output
10564

ID: 247Y1A6790
16

Test Case - 2

User Output
12345
15

Test Case - 3

2024-2028-CSD-B
User Output
555555
Invalid input

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
1001
Invalid input
Date: 2024-12-
S.No: 49 Exp. Name: For loop in C

Page No: 98
03

Aim:
Write a program that takes two integers as input, start and end. The program should use

ID: 247Y1A6790
a for loop to iterate from start to end (both inclusive).

Input Format:
• Input contains two space-separated integers a and b, representing the start and
end values.

Constraints:
•1≤a < b ≤ 10
6

Output Format:
• Return a space-separated list of integers from a to b, If the input is valid (i.e., a is

2024-2028-CSD-B
less than or equal to b)
• Return "Invalid input", If the input is invalid (i.e., a is greater than b)
Source Code:

integers.c

#include<stdio.h>

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int main(){
int start, end;
scanf("%d%d", &start, &end);
if (start > end){
printf("Invalid input\n");
}
else {
for (int i = start; i <= end; i++){
printf("%d", i);
if (i <= end){
printf(" ");
}
}
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 99
User Output
19
1 2 3 4 5 6 7 8 9

ID: 247Y1A6790
Test Case - 2

User Output
8 11
8 9 10 11

Test Case - 3

2024-2028-CSD-B
User Output
12 21
12 13 14 15 16 17 18 19 20 21

Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
102 30
Invalid input
Date: 2024-12-
S.No: 50 Exp. Name: Food Chain

Page No: 100


03

Aim:
Write a C program that takes the input for multiple test cases. For each test case, the
program should receive two integers, E and K , representing the energy at the lowest

ID: 247Y1A6790
trophic level and the energy reduction factor, respectively. The program should calculate
and display the maximum length of the food chain for each test case.

Input Format:
• The first line contains an integer N - the number of test cases. Then the test cases
follow.
• Each test case contains a single line of input, two integers E,K .
Constraints:
• 1 ≤ N ≤ 10 4

• 1 ≤ E, K ≤ 10 9

2024-2028-CSD-B
Output Format:
• Return the length of the food chain for each test case.

Sample Test Case:


3
53
2

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


67
1
10 2
4
Explanation:
#Testcase1: The energy at different levels is:
• level 1 - 5 units
• level 2 - = 1 units
5

So the length of the food chain is2 since from the next level onwards0 units of energy will
be received.

#Testcase2: The food chain length is 1 because the initial energy (6) is less than the
energy reduction factor (7), so the chain ends immediately after one step.

#Testcase3: The energy at different levels is:


• level 1 - 10 units
• level 2 - = 5 units
10

• level 3 - units
5
= 2
2

• level 4 - 2

2
= 1 units
• level 5 - 1

2
= 0 units
So the length of the food chain is 4 since it is the last level to receive non-zero energy.
Source Code:

Page No: 101


foodchain.c

#include<stdio.h>
int main (){
int T;
scanf("%d", &T);

ID: 247Y1A6790
while (T--){
int energy, reductionFactor;
scanf("%d%d", &energy, &reductionFactor);
int length = 0;
while(energy > 0){
length++;
energy /= reductionFactor;
}
printf("%d\n", length);
}

2024-2028-CSD-B
return 0;
}

Execution Results - All test cases have succeeded!

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 1

User Output
3
53
2
67
1
10 2
4

Test Case - 2

User Output
1
10 10
2
3
1
3
1
3

2
3

15
12

15 3
50 5

100 10

User Output
User Output

Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 102
Date: 2024-12-
S.No: 51 Exp. Name: Multiplication table

Page No: 103


03

Aim:
Write a program in C that takes an integer, n, as input, representing the number of
multiplication tables to be generated. The program should output the multiplication table

ID: 247Y1A6790
for each number from 1 to n, up to a multiple of 10.

Input Format:
• A single integer n represents the number of times the multiplication table should
be printed.

Constraints:
•1≤n ≤ 20

Output Format:

2024-2028-CSD-B
• Multiplication tables from 1 to 10 for each number from 1 to n.
Source Code:

multiple.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int N;
scanf("%d", &N);
for (int i = 1; i <= N; i++){
printf("%d:\n", i);
for (int j = 1; j <= 10; j++){
printf("%d x %d = %d\n", i, j, i * j);
}
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
1:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3

Page No: 104


1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8

ID: 247Y1A6790
1 x 9 = 9
1 x 10 = 10
2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12

2024-2028-CSD-B
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
4
1:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10
2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 6 = 12
2 x 7 = 14

Page No: 105


2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
3:
3 x 1 = 3

ID: 247Y1A6790
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30

2024-2028-CSD-B
4:
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

Test Case - 3

User Output
1
1:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 10 = 10

Page No: 106


Test Case - 4

User Output
3

ID: 247Y1A6790
1:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8

2024-2028-CSD-B
1 x 9 = 9
1 x 10 = 10
2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Date: 2024-12-
S.No: 52 Exp. Name: Favourite Numbers

Page No: 107


03

Aim:
Alice, Bob, and Charlie have different preferences for numbers. Alice likes numbers that
are even and multiples of 7, while Bob prefers numbers that are odd and multiples of 9.

ID: 247Y1A6790
They have found a number, A, and the task is to determine who takes it home.
Write a program that takes an integer, A, as input and outputs the person who takes the
number home based on their preferences. If A is an even multiple of 7, Alice takes it
home. If A is an odd multiple of 9, Bob takes it home. If neither Alice nor Bob likes the
number, Charlie takes it home.

Input Format:
• Input consists of a single integer A.
Output Format:
• Return the name of the person (Alice, Bob, Charlie) based on the given conditions.

2024-2028-CSD-B
Source Code:

favNum.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%d", &number);
if (number % 2 == 0 && number % 7 == 0){
printf("Alice\n");
} else if (number % 2 != 0 && number % 9 == 0){
printf("Bob\n");
} else {
printf("Charlie\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
14
Alice
63
15
27

Bob
Bob

Charlie

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 108
Date: 2024-12-
S.No: 53 Exp. Name: Can Chef

Page No: 109


03

Aim:
Chef owns a car that can run 15 kilometres using 1 litre of petrol. He wants to attend a
programming camp at DAIICT, which is a distance of Y kilometres from his house. Chef

ID: 247Y1A6790
currently has X litres of petrol in his car. The task is to determine whether Chef can
attend the event at DAIICT and return to his home with the given amount of petrol.
Note: Chef has to return back to home, so the total distance to be covered would be 2. Y

Input Format:
• The input contains two space-separated integers X and Y - the amount of petrol
in litre and the distance between Chef's house and DAIICT in kilometres,
respectively
Constraints:
• 1 ≤ x ≤ 10 2

2024-2028-CSD-B
Output Format:
• Return YES if it is possible for the chef to attend the event and return home, else,
return NO.
Source Code:

distance.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main(){
int petrol, distance;
scanf("%d%d", &petrol, &distance);
int totalDistance = 2 * distance;
int distanceCovered = 15 * petrol;
if (distanceCovered >= totalDistance){
printf("YES\n");
} else {
printf("NO\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
NO

YES
YES
YES

8 30

12 40
10 50

15 200

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 110
Exp. Name: Finding the Height of the Date: 2024-12-
S.No: 54

Page No: 111


Pyramid 03

Aim:
Listen to this story: a boy and his father, a computer programmer, are playing with
wooden blocks. They are building a pyramid.Their pyramid is a bit weird, as it is actually a

ID: 247Y1A6790
pyramid-shaped wall - it's flat. The pyramid is stacked according to one simple principle:
each lower layer contains one block more than the layer above.The figure illustrates the
rule used by the builders:

2024-2028-CSD-B
Note: the height is measured by the number of fully completed layers - if the builders
don't have a sufficient number of blocks and cannot complete the next layer, they finish
their work immediately.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Input Format:
Single line of input contains an integer n representing the number of blocks

Constraints:
1 <= n <= 1000

Output Format:
Print the height of the pyramid

Example:
Input:
6

Output:
3

Explanation: Observe the given figure in the question description, with 6 blocks, we can
build a pyramid of height 3.
Source Code:

HeightOfPyramid.c
#include<stdio.h>

Page No: 112


int main(){
int n;
scanf("%d", &n);
int height = 0;
int blocksNeeded=1;
while (n >= blocksNeeded){

ID: 247Y1A6790
n -= blocksNeeded;
height++;
blocksNeeded++;
}
printf("%d\n", height);
return 0;
}

2024-2028-CSD-B
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
6

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3

Test Case - 2

User Output
100
13

Test Case - 3

User Output
1000
44

Test Case - 4

User Output
12
9
4

45
User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 113
Date: 2025-01-
S.No: 55 Exp. Name: Special Number

Page No: 114


02

Aim:
Write a C program that allows the user to find a number such that its double is greater
than its half by a specified target difference value. If such a number exists, the program

ID: 247Y1A6790
should print Yes, otherwise, it should print No
Source Code:

SpecialNumber.c
#include<stdio.h>
int main()
{
static float x,y;
scanf("%f%f",&y ,&x);

2024-2028-CSD-B
if((2*x -x/2) == y)
printf("Yes\n");
else
printf("No\n");
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
45.0
30.0
Yes

Test Case - 2

User Output
135
90.0
Yes

Test Case - 3
No
No
No

15
30.0
60.0
50.0
30.5
45.0

User Output
User Output
User Output

Test Case - 5
Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 115
Exp. Name: Minimum Attendance Date: 2025-01-
S.No: 56

Page No: 116


Requirement 02

Aim:
Chef is a student at a university, and the university has a requirement that students must
be present for at least 75% of the working days in a semester to pass. The semester has a

ID: 247Y1A6790
total of 120 working days. Chef has been taking a lot of holidays and is worried about
meeting the attendance requirement. The information about the days Chef has attended
or been absent is given as a sequence of N bits: B1, B2, ..., BN. If Bi = 0, it means Chef was
absent on the ith day, and if Bi = 1, it means Chef was present on that day. The task is to
determine if Chef can pass the attendance requirement by the end of the semester.

Write a program that takes an integer N as input, followed by a sequence of N bits, and
outputs whether Chef can hope to pass the attendance requirement or not.

Input Format:

2024-2028-CSD-B
First line of input contains an integer N representing the no of days till now
Second line of input contains a string B of length N where Bi represents the status of the
ith day.

Output Format:
Print"Yes" if Chef can pass the attendance requirement and "N0" if not

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Constraints:
1 <= N <= 120
0 <= Bi <= 1

Example:
Input:
50
00000000000000000000000000000000000000000000000000

Output:
No

Explanation:
Even if Chef attends all the remaining 70 days, he'll only have an attendance percentage
of70/120 =58.33% which is less than75%.
Source Code:

attendanceRequirement.c
#include<stdio.h>

Page No: 117


#include<string.h>
int main()
{
static int n,a;
char r;
scanf("%i",&n);

ID: 247Y1A6790
char s[n];
scanf("%s",s);
for(int i=0;i<n;i++)
{
r=s[i];
if(r==48)
a++;
}
if(a>30)
printf("No\n");

2024-2028-CSD-B
else
printf("Yes\n");
}

Execution Results - All test cases have succeeded!

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 1

User Output
50
00000000000000000000000000000000000000000000000000
No

Test Case - 2

User Output
2
01
Yes

Test Case - 3

User Output
10
0101011010

Page No: 118


Yes

Test Case - 4

ID: 247Y1A6790
User Output
45
000000000000000000000000000000000000000000000
No

Test Case - 5

User Output

2024-2028-CSD-B
60
000000000000000000000000000000000000000000000000000000000000
No

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Date: 2025-01-
S.No: 58 Exp. Name: Number Pattern

Page No: 119


02

Aim:
Write a C program for printing the number pattern for given N

ID: 247Y1A6790
Example:
N=5

Output:
12345
1234
123
12
1
Source Code:

2024-2028-CSD-B
numberPattern.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%i",&n);
for(int i=n;i>0;i--)
{
for(int j=1;j<=i;j++)
{
printf("%i ",j);
}
printf("\n");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
1 2
1
1
1

1
5

1 2
1 2 3
1 2 3 4
1 2 3 4 5

User Output
User Output

Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 120
Date: 2025-01-
S.No: 59 Exp. Name: Decrement OR Increment

Page No: 121


02

Aim:
Write a C program to obtain a number N and increment its value by 1 if the number is
divisible by 4 otherwise decrement its value by 1.

ID: 247Y1A6790
Source Code:

IncrementOrDecrement.c
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
if(n%4==0)

2024-2028-CSD-B
{
n++;
}
else
{
n--;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


printf("%d",n);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
4

Test Case - 2

User Output
100
101
17
16
229
241

230
240

User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 122
Exp. Name: Incrementing the integer by Date: 2024-12-
S.No: 60

Page No: 123


one. 18

Aim:
Given a large integer represented as an integer array of digits, where each digits[i] is the
i-th digit of the integer, ordered from most significant to least significant in left-to-right

ID: 247Y1A6790
order (without any leading zeros). Implement a program to increment the large integer
by one and return the resulting array of digits.

Input Format:
• The first line contains an integer 'digitsSize', representing the number of digits.
• The second line contains space-separated integers (digits) representing the digits
of the large integer.
Constraints:
• 1 ≤ digitsSize ≤ 100
• 0 ≤ digits[i] ≤ 9

2024-2028-CSD-B
• digits do not contain any leading 0's.
Output Format:
• Return comma-separated digits of incremented large integer.

Sample Test Case:


3
123

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


1,2,4
Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 =
124. Thus, result would be 1,2,4.
Source Code:

increment.c
#include <stdio.h>

Page No: 124


int main() {
int digitsSize;
scanf("%d", &digitsSize); // Read the size of the digits array

int digits[digitsSize]; // Array to store the digits of the large


number

ID: 247Y1A6790
// Read the digits of the large number
for (int i = 0; i < digitsSize; i++) {
scanf("%d", &digits[i]);
}

// Start from the last digit and increment


int carry = 1; // We need to increment by 1
for (int i = digitsSize - 1; i >= 0; i--) {
if (carry == 0) {

2024-2028-CSD-B
break; // No carry, no need to continue
}

digits[i] += carry; // Add the carry to the current digit

if (digits[i] == 10) {
digits[i] = 0; // Set the digit to 0 and carry over 1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


carry = 1; // Keep the carry going
} else {
carry = 0; // No more carry needed
}
}

// If there's still a carry left, we need to add an extra digit at the


front
if (carry == 1) {
// Shift all digits to the right by 1 and insert 1 at the front
for (int i = digitsSize - 1; i >= 0; i--) {
digits[i + 1] = digits[i];
}
digits[0] = 1;
digitsSize++; // Increase the size of the digits array by 1
}

// Print the result as comma-separated values


for (int i = 0; i < digitsSize; i++) {
if (i > 0) {
printf(",");
}
printf("%d", digits[i]);

Page No: 125


}

printf("\n"); // Print a newline after the result


return 0;
}

ID: 247Y1A6790
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
4
4321

2024-2028-CSD-B
4,3,2,2

Test Case - 2

User Output
1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


9
1,0

Test Case - 3

User Output
3
123
1,2,4

Test Case - 4

User Output
3
527
5,2,8
Exp. Name: Determine the number of Date: 2024-12-
S.No: 61

Page No: 126


weeks in which the Chef met his target. 17

Aim:
Chef has set a target to solve at least 10 problems every week for a duration of 4 weeks.
Your task is to determine the number of weeks in which the Chef met his target.

ID: 247Y1A6790
Input Format:
• The input consists of 4 integers representing the number of problems Chef solved
in each week (P 1, P 2, P 3, and P 4).
Output Format:
• The output should be a single integer indicating the count of weeks where Chef
solved at least 10 problems.

Sample Test Case:


12 15 8 10

2024-2028-CSD-B
3
Explanation: Chef solved at least 10 problems in the first, second and fourth weeks. He
failed to solve at least 10 problems in the third week. Hence, the number of weeks in
which Chef met his target is 3.
Source Code:

week.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>
int main ()
{
int target=10;
int problems[4];
for (int i=0; i<4; i++){
scanf("%d", &problems[i]);
}
int count=0;
for(int i=0; i<4; i++){
if(problems[i]>= target){
count++;
}
}
printf("%d\n",count);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 127


User Output
12 15 8 10
3

ID: 247Y1A6790
Test Case - 2

User Output
2 3 1 10
1

Test Case - 3

2024-2028-CSD-B
User Output
12 100 99 11
4

Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
1111
0
Date: 2024-12-
S.No: 62 Exp. Name: Practice Program

Page No: 128


17

Aim:
Chef recently revamped its practice page to make it easier for users to identify the next
problems they should solve by introducing some new features:

ID: 247Y1A6790
• Recent Contest Problems - contains only problems from the last 2 contests
• Separate Un-Attempted, Attempted, and All tabs.
• Problem Difficulty Rating - the Recommended dropdown menu has various
difficulty ranges so that you can attempt the problems most suited to your
experience
• Popular Topics and Tags
Like most users, Chef didn’t know that he could add problems to a personal to-do list by
clicking on the magic '+' symbol on the top-right of each problem page. But once he
found out about it, he went crazy and added loads of problems to his to-do list without
looking at their difficulty rating. Chef is a beginner and should ideally try and solve only

2024-2028-CSD-B
problems with difficulty rating strictly less than 1000.

Given a list of difficulty ratings for problems in the Chef’s to-do list, please help him
identify how many of those problems Chef should remove from his to-do list, so that he
is only left with problems of difficulty rating less than 1000.

Input Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The first line of input contains an integer N , representing the total number of
problems that the Chef has added to his to-do list.
• The second line of input contains N space-separated integers D , D , . . , D ,
1 2 n

which are the difficulty ratings for each problem in the to-do list.

Constraints:
•1≤N ≤ 1000

•1≤D i ≤ 5000

Output Format:
• Return the number of problems that Chef will have to remove so that all remaining
problems have a difficulty rating strictly less than 1000
Source Code:

PracticeProgram.c
#include<stdio.h>

Page No: 129


int main()
{
int n;
scanf("%d", &n);
int count = 0;
int difficulty;

ID: 247Y1A6790
for (int i = 0; i < n; i++){
scanf("%d", &difficulty);
if(difficulty >= 1000){
count++;
}
}
printf("%d\n", count);
return 0;
}

2024-2028-CSD-B
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3
900 700 800
0

Test Case - 2

User Output
3
800 1200 900
1

Test Case - 3

User Output
4
999 1000 1001 1002
3
1
5
1 2 2 2 5000
User Output
Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 130
Date: 2024-12-
S.No: 63 Exp. Name: Maximize the profit

Page No: 131


18

Aim:
You are given an array price where prices[i] is the price of a given stock on the ith day. You
want to maximize your profit by choosing a single day to buy one stock and choosing a

ID: 247Y1A6790
different day in the future to sell that stock.

Input format:
• The first line contains an integer (pricesSize) representing the number of days.
• The second line contains space-separated (pricesSize) integers representing the
stock prizes for each day.

Constraints:
• 1 ≤ pricesSize ≤ 10 5

• 0 ≤ prices[i] ≤ 10 4

2024-2028-CSD-B
Output Format:
• Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.

Sample Test Case:


6

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


715364
5
Explanation: The maximum profit is achieved by buying on day 2 (price = 1) and selling
on day 5 (price = 6), resulting in a profit of 5 (6 - 1 = 5).
Source Code:

profit.c
#include <stdio.h>

Page No: 132


int main() {
int pricesSize;
scanf("%d", &pricesSize);

int prices[pricesSize];

ID: 247Y1A6790
// Read stock prices for each day
for (int i = 0; i < pricesSize; i++) {
scanf("%d", &prices[i]);
}

// Initialize variables to track minimum price and maximum profit


int min_price = prices[0];
int max_profit = 0;

// Loop through the prices array

2024-2028-CSD-B
for (int i = 1; i < pricesSize; i++) {
// Calculate potential profit if sold on the current day
int potential_profit = prices[i] - min_price;

// Update max_profit if we found a higher profit


if (potential_profit > max_profit) {
max_profit = potential_profit;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}

// Update min_price if we find a lower price


if (prices[i] < min_price) {
min_price = prices[i];
}
}

// Output the maximum profit


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

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
3
5
0

2
4
6
5

16
1234
76431

715364

User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 133
Date: 2024-12-
S.No: 64 Exp. Name: Find the odd one out

Page No: 134


17

Aim:
Given a non-empty array of integers nums, every element appears twice except for one.
Find that single one.

ID: 247Y1A6790
You must implement a solution with a linear runtime complexity and use only constant
extra space.

Input Format:
• The first line contains an integer numsSize representing the number of elements in
the array.
• The second line contains numsSize integers representing the elements of the array.

Constraints:

2024-2028-CSD-B
• 1 ≤ nums.size ≤ 10 4

• −10 ≤ nums[i] ≤ 10
4 4

• Each element in the array appears twice except for one element which appears
only once.

Output Format:
• Return an integer which is the single number in the array.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

element.c
#include<stdio.h>
int main()
{
int numsSize;
scanf("%d", &numsSize);
int nums[numsSize];
for(int i=0; i<numsSize; i++){
scanf("%d", &nums[i]);
}
int result=0;
for (int i=0; i< numsSize; i++){
result ^= nums[i];
}
printf("%d\n", result);
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 135


Test Case - 1

User Output
3

ID: 247Y1A6790
221
1

Test Case - 2

User Output
5
41212
4

2024-2028-CSD-B
Test Case - 3

User Output
1
1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


1

Test Case - 4

User Output
5
66474
7
Date: 2024-12-
S.No: 65 Exp. Name: Majority Element

Page No: 136


17

Aim:
Given an array nums of size n, return the majority element. The majority element is the
element that appears more than ⌊n/2⌋ times. You may assume that the majority element

ID: 247Y1A6790
always exists in the array.

Input Format:
• The first line contains an integer n representing the number of elements in the
array.
• The second line contains n integers representing the elements of the array.
Output Format:
• An integer representing the majority element that appears more than ⌊n/2⌋ times
in the array.
Source Code:

2024-2028-CSD-B
majority.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%d", &n);
int nums[n];
for (int i = 0; i < n; i++){
scanf("%d", &nums[i]);
}
int candidate = nums[0];
int count = 1;
for (int i=1; i < n; i++){
if (nums[i] == candidate){
count++;
}else{
count--;
}
if(count == 0){
candidate = nums[i];
count=1;
}
}
printf("%d\n", candidate);
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 137


Test Case - 1

User Output
3

ID: 247Y1A6790
323
3

Test Case - 2

User Output
7
2211122
2

2024-2028-CSD-B
Test Case - 3

User Output
2
33

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3

Test Case - 4

User Output
5
66474
4
Date: 2024-12-
S.No: 66 Exp. Name: Small Factorials

Page No: 138


17

Aim:
Write a C program to calculate the factorial of small positive integers

ID: 247Y1A6790
Input Format:
Single line of input contains an integer N representing the value to find the factorial

Output Format:
Print the factorial result of N

Source Code:

factorial.c

2024-2028-CSD-B
#include<stdio.h>
int main()
{
int N;
scanf("%d", &N);
long long int result = 1;
for (int i = 1; i <= N; i++){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


result *= i;
}
printf("%lld\n", result);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
2

Test Case - 2

User Output
3
1
6

1
5
4
24

120

User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 139
Date: 2024-12-
S.No: 67 Exp. Name: On a Way to Market

Page No: 140


17

Aim:
You're on your way to the market and meet a man who has multiple wives. Each wife has
x no of bags, and each bag contains y number of dogs, with each dog having z no of

ID: 247Y1A6790
puppies. Write a C program that takes input for the number of wives, bags per wife, dogs
per bag, and puppies per dog. Calculate and display the total number of living beings
(not including yourself) that are going to the market.

Input Format:
First line of input contains the number of wives
Second line of input contains the number of bags per wife
Third line of input contains the number of dogs per bag
Fourth line of input contains the number of puppies per dog

2024-2028-CSD-B
Output Format:
Print the total no of living beings going to the market

Constraints:
1 <= no of wives <= 10
1 <= x <= 10
0 <= y, z <= 10

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

NoOfBeings.c

#include<stdio.h>
int main ()
{
int w, x, y, z;
scanf("%d", &w);
scanf("%d", &x);
scanf("%d", &y);
scanf("%d", &z);
int totalLivingBeings = w + (w * x * y) + (w * x * y * z);
printf("%d\n", totalLivingBeings+1);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 141


User Output
4
4
4

ID: 247Y1A6790
4
325

Test Case - 2

User Output
1
2

2024-2028-CSD-B
1
9
22

Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
1
1
0
0
2

Test Case - 4

User Output
3
1
1
2
13
3
1
2
1

10
User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 142
Date: 2024-12-
S.No: 68 Exp. Name: Pretty Numbers

Page No: 143


17

Aim:
Lahya likes the number 239. Therefore, she considers a number pretty if its last digit is 2
or 3 or 9. Lahya wants to watch the numbers between L and R (both inclusive), so she

ID: 247Y1A6790
asked you to determine how many pretty numbers are in this range. Can you help her?

Input Format:
• A single line of input contains two space-separated integersL andR

Output Format:
• Print the total no of Pretty numbers between L and R

Constraints:
• 1 <= L <= R <=105

2024-2028-CSD-B
Source Code:

CountingPrettyNums.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int L, R;
scanf("%d %d", &L, &R);
int count = 0;
for (int i = L; i <= R; i++){
int last_digit = i % 10;
if (last_digit == 2 || last_digit == 3 || last_digit ==
9){
count++;
}
}
printf("%d\n", count);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1 11
3

Page No: 144


Test Case - 2

User Output

ID: 247Y1A6790
11 35
8

Test Case - 3

User Output
1 100
30

2024-2028-CSD-B
Test Case - 4

User Output
100 599
150

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
1 599
180
Date: 2024-12-
S.No: 69 Exp. Name: What is your Score?

Page No: 145


18

Aim:
You are participating in a contest which has 11 problems (numbered 1 through 11). The
first eight problems (i.e. problems 1,2,…,8) are scorable, while the last three problems (9,10

ID: 247Y1A6790
and 11) are non-scorable - this means that any submissions you make on any of these
problems do not affect your total score.
Your total score is the sum of your best scores for all scorable problems. That is, for each
scorable problem, you look at the scores of all submissions you made on that problem
and take the maximum of these scores (or 0 if you didn't make any submissions on that
problem); the total score is the sum of the maximum scores you took.

You know the results of all submissions you made. Calculate your total score.

Input Format:

2024-2028-CSD-B
First line of input contains a single integerN denoting the number of submissions you
made
Next N lines follow. For eachi (1 ≤ i ≤ N), theith of these lines contains two space-
separated integerspiandsi, denoting that youri-th submission was on problempi and it
received a scoresi

Output Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Print your total score

Constraints:
1 <= N <= 1000
1 <= pi<= 11 for each validi
0 <= si <= 100 for each validi
Source Code:

TotalScore.c
#include <stdio.h>

Page No: 146


int main() {
int N;
scanf("%d", &N); // Read the number of submissions

// Initialize an array to track the maximum scores for problems 1


through 8

ID: 247Y1A6790
int max_scores[8] = {0}; // Initialize all scores to 0

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


int pi, si;
scanf("%d %d", &pi, &si); // Read problem number and score

// We are only interested in problems 1 through 8 (scorable problems)


if (pi >= 1 && pi <= 8) {
int index = pi - 1; // Map problem number to array index (0-based)
if (si > max_scores[index]) {

2024-2028-CSD-B
max_scores[index] = si; // Update the max score for this problem
}
}
}

// Calculate the total score as the sum of max scores for problems 1
through 8

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int total_score = 0;
for (int i = 0; i < 8; i++) {
total_score += max_scores[i];
}

// Output the total score


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

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1
11 1
0
Test Case - 2

Page No: 147


User Output
5
2 45
9 100

ID: 247Y1A6790
80
2 15
89
54

Test Case - 3

User Output

2024-2028-CSD-B
3
80
2 15
2 46
46

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
1
100 125
0

Test Case - 5

User Output
3
100 200
12 15
12 156
0
Date: 2024-12-
S.No: 70 Exp. Name: Matrix Multiplication

Page No: 148


18

Aim:
Write a C program to help Joe and Lilly multiply two matrices, A and B. The program
should take input for multiple test cases. For each test case, the program should read the

ID: 247Y1A6790
dimensions and values of matrices A and B. If the multiplication is possible, the program
should print the output matrix values. If the multiplication is not possible, the program
should print "IMPOSSIBLE"

Input Format:
• The first line contains a number, t, denoting the number of test cases.
• Next line is to take the no.of rows & columns of matrix A separated with space.
• After that take the matrix values of A separated with space.
• Next line is to take the no.of rows & columns of matrix B separated with space.
• After that take the matrix values of B separated with space.

2024-2028-CSD-B
Constraints:
• 1 ≤ t ≤ 100
• 1 ≤ A[i,j] ≤ 1000
• 1 ≤ B[i,j] ≤ 1000
Output Format:
• If the multiplication is possible, then print the output matrix values separated with
space.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• else print "IMPOSSIBLE" (without quotes).
Source Code:

Matrix.c
#include <stdio.h>

Page No: 149


void multiplyMatrices(int A[][100], int B[][100], int C[][100], int
A_rows, int A_cols, int
B_rows, int B_cols) {
for (int i = 0; i < A_rows; i++) {
for (int j = 0; j < B_cols; j++) {
C[i][j] = 0;

ID: 247Y1A6790
for (int k = 0; k < A_cols; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
int main() {
int t;
scanf("%d", &t);
while (t--) {

2024-2028-CSD-B
int A_rows, A_cols, B_rows, B_cols;
int A[100][100], B[100][100], C[100][100];
scanf("%d %d\n", &A_rows, &A_cols);
for (int i = 0; i < A_rows; i++) {
for (int j = 0; j < A_cols; j++) {
scanf("%d", &A[i][j]);
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
scanf("%d %d", &B_rows, &B_cols);
for (int i = 0; i < B_rows; i++) {
for (int j = 0; j < B_cols; j++) {
scanf("%d", &B[i][j]);
}
}
if (A_cols != B_rows) {
printf("IMPOSSIBLE\n");
} else {
multiplyMatrices(A, B, C, A_rows, A_cols, B_rows, B_cols);
for (int i = 0; i < A_rows; i++) {
for (int j = 0; j < B_cols; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
}printf("\n");
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 150


Test Case - 1

User Output
3

ID: 247Y1A6790
22
1234
22
1111
3 3
7 7
13
123
32

2024-2028-CSD-B
100110
4 2
13
345
12
89

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


IMPOSSIBLE

Test Case - 2

User Output
1
23
123456
33
7 8 9 10 11 12 13 14 15
66 72 78
156 171 186

Test Case - 3

User Output
1
32

76 82

292 316
184 199
123456789

10 11 12 13 14 15

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 151
Date: 2024-12-
S.No: 71 Exp. Name: Search a given Matrix

Page No: 152


18

Aim:
You are given an m x n integer matrix with the following two properties:
• Each row is sorted in non-decreasing order.

ID: 247Y1A6790
• The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return true if target is in matrix or false otherwise.

Input Format:
• The first line contains two integers, m and n, representing the number of rows and
columns of the matrix.
• The following m lines each contain n integers, representing the elements of the
matrix row-wise.
• The last line contains an integer, target, representing the target element to search

2024-2028-CSD-B
for in the matrix.
Constraints:
• m == matrix.length
• n == matrix[i].length
• 1 <= m, n <= 100
• -104 <= matrix[i][j], target <= 104
Output Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• If the target element is found in the matrix, the program should print "true", else
"false"
Source Code:

Matrix.c
#include <stdio.h>

Page No: 153


int searchMatrix(int matrix[][100], int m, int n, int target) {
int left = 0, right = m * n - 1;

while (left <= right) {


int mid = left + (right - left) / 2;
int mid_val = matrix[mid / n][mid % n];

ID: 247Y1A6790
if (mid_val == target) {
return 1; // target found
} else if (mid_val < target) {
left = mid + 1; // search in the right half
} else {
right = mid - 1; // search in the left half
}
}
return 0; // target not found

2024-2028-CSD-B
}
int main() {
int m, n, target;

// Read the number of rows and columns


scanf("%d %d", &m, &n);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int matrix[100][100];

// Read the matrix


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

// Read the target element


scanf("%d", &target);

// Call the search function and print the result


if (searchMatrix(matrix, m, n, target)) {
printf("true\n");
} else {
printf("false\n");
}

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 154


Test Case - 1

User Output
34

ID: 247Y1A6790
1357
10 11 16 20
23 30 34 60
3
true

Test Case - 2

User Output

2024-2028-CSD-B
34
1357
10 11 16 20
23 30 34 60
13
false

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
22
12
34
4
true

Test Case - 4

User Output
23
123
456
0
false

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 155
Date: 2024-12-
S.No: 72 Exp. Name: Richest Customer Wealth

Page No: 156


18

Aim:
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money
the ith customer has in the jth bank. Return the wealth that the richest customer has. A

ID: 247Y1A6790
customer's wealth is the amount of money they have in all their bank accounts. The
richest customer is the customer that has the maximum wealth.

Input Format:
• First line,the number of customers
• Second line, the number of banks
• Third line, the wealth of each customer in each bank, and the output format
provides the maximum wealth among all customers.
Constraints:
• m == accounts.length

2024-2028-CSD-B
• n == accounts[i].length
• 1 <= m, n <= 50
• 1 <= accounts[i][j] <= 100
Output Format:
• Return the maximum wealth among all customers.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


wealth.c
#include <stdio.h>

Page No: 157


int maximumWealth(int accounts[][50], int m, int n) {
int maxWealth = 0;

// Iterate over each customer


for (int i = 0; i < m; i++) {
int customerWealth = 0;

ID: 247Y1A6790
// Sum up the wealth for the current customer
for (int j = 0; j < n; j++) {
customerWealth += accounts[i][j];
}

// Update maxWealth if the current customer has more wealth


if (customerWealth > maxWealth) {
maxWealth = customerWealth;
}

2024-2028-CSD-B
}

return maxWealth;
}
int main() {
int m, n;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// Read the number of customers and banks
scanf("%d", &m);
scanf("%d", &n);

int accounts[m][50]; // Matrix to store the wealth of each customer in


each bank

// Read the wealth for each customer


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

// Call the function to calculate and print the maximum wealth


int result = maximumWealth(accounts, m, n);
printf("%d\n", result);

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 158


Test Case - 1

User Output
2

ID: 247Y1A6790
2
15
25
7

Test Case - 2

User Output
3

2024-2028-CSD-B
2
15
73
35
10

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
2
3
234
567
18

Test Case - 4

User Output
1
1
100
100
Date: 2024-12-
S.No: 73 Exp. Name: Matrix Diagonal Sum

Page No: 159


18

Aim:
Given a square matrix mat, return the sum of the matrix diagonals.

ID: 247Y1A6790
Only include the sum of all the elements on the primary diagonal and all the elements on
the secondary diagonal that are not part of the primary diagonal.

Example:

2024-2028-CSD-B
Input:
3 size of the matrix. i.e., 3 × 3 Matrix
123 Subsequent lines contain matrix elements separated by spaces, representing a

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


row of the matrix.
456
789

 utput:
O
25 Sum of the primary diagonal and the secondary diagonal (excluding the
elements that are part of the primary diagonal).

Explanation:
Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.

Constraints:
• n == mat.length == mat[i].length
• 1 <= n <= 100
• 1 <= mat[i][j] <= 100
Source Code:

diagonalSum.c
#include <stdio.h>

Page No: 160


int diagonalSum(int mat[][100], int n) {
int sum = 0;

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


// Add the element from the primary diagonal
sum += mat[i][i];

ID: 247Y1A6790
// Add the element from the secondary diagonal
sum += mat[i][n - 1 - i];
}

// If the matrix size is odd, subtract the center element once (it was
counted twice)
if (n % 2 != 0) {
sum -= mat[n / 2][n / 2];
}

2024-2028-CSD-B
return sum;
}
int main() {
int n;

// Read the size of the matrix

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%d", &n);

int mat[100][100]; // Matrix to store the elements

// Read the matrix elements


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

// Call the function to calculate and print the diagonal sum


int result = diagonalSum(mat, n);
printf("%d\n", result);

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 161


User Output
3
123
456

ID: 247Y1A6790
789
25

Test Case - 2

User Output
4
1111

2024-2028-CSD-B
1111
1111
1111
8

Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
2
12
34
10

Test Case - 4

User Output
5
10001
02020
00300
02020
10001
15
Exp. Name: Multiplication of two Date: 2024-12-
S.No: 74

Page No: 162


Matrices 18

Aim:
Write a program to perform matrix multiplication. If Multiplication cannot be done for the
given matrices, then print "Not Possible"

ID: 247Y1A6790
Input Format:
• First line of input contains two space separated integers, no of rows (r1) and
columns (c1) of matrix 1
• Next r1 lines contains c1 no of elements of matrix 1, separated by space
• Next line of input contains two space separated integers, no of rows (r2) and
columns (c2) of matrix 2
• Next r2 lines contains c2 no of elements of matrix 2, separated by space

Output Format:

2024-2028-CSD-B
• Print the result after multiplying the two matrices, if multiplication is not possible,
print "Not Possible"

Constraints:
• 1 <= r1, c1, r2, c2 <= 10
• 0 <= matrix1[i], matrix2[i] <= 100
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


MatrixMultiplication.c
#include <stdio.h>

Page No: 163


void multiplyMatrices(int A[][10], int B[][10], int C[][10], int r1,
int c1, int r2, int c2)
{
if (c1 != r2) {
printf("Not Possible\n");
return;

ID: 247Y1A6790
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
C[i][j] = 0;
}
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];

2024-2028-CSD-B
}
}
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d ", C[i][j]);
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


printf("\n");
}
}
int main() {
int r1, c1, r2, c2;
scanf("%d %d", &r1, &c1);
int A[10][10];
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
scanf("%d", &A[i][j]);
}
}
scanf("%d %d", &r2, &c2);
int B[10][10];
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
scanf("%d", &B[i][j]);}
}
// Result matrix
int C[10][10];
// Call function to multiply matrices
multiplyMatrices(A, B, C, r1, c1, r2, c2);
return 0;

Page No: 164


}

Execution Results - All test cases have succeeded!

ID: 247Y1A6790
Test Case - 1

User Output
22
12
34
22
12

2024-2028-CSD-B
34
7 10
15 22

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
33
123
456
789
23
123
456
Not Possible

Test Case - 3

User Output
22
11 22
33 44
22
33 44
847 1210

Page No: 165


1815 2662

Test Case - 4

ID: 247Y1A6790
User Output
23
123
456
32
12
34
56

2024-2028-CSD-B
22 28
49 64

Test Case - 5

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


11
5
22
36
9 12
Not Possible
Exp. Name: Median of Two Sorted Date: 2024-12-
S.No: 75

Page No: 166


Arrays 18

Aim:
Given two sorted arrays arr1 and arr2 of size m and n respectively, return the median of
the two sorted arrays.

ID: 247Y1A6790
Input Format:
First line of input contains an integer m
Second line of input contains m space separated integer elements of arr1
Third line of input contains an integer n
Fourth line of input contains n space separated integer elements of arr2

Output Format:
Print the median of the given two sorted arrays

2024-2028-CSD-B
Constraints:
1 <= m, n <= 1000
0 <= arr1[i], arr2[i] <= 10000
1 <= m + n <= 2000
Source Code:

MedianofTwoArrays.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 167


void findMedian(int arr1[], int m, int arr2[], int n) {
float merged[m + n]; // Array to store the merged result
int i = 0, j = 0, k = 0;
// Merge the two arrays
while (i < m && j < n) {
if (arr1[i] <= arr2[j]) {

ID: 247Y1A6790
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
// If any elements are left in arr1
while (i < m) {
merged[k++] = arr1[i++];
}
// If any elements are left in arr2

2024-2028-CSD-B
while (j < n) {
merged[k++] = arr2[j++];
}
// Calculate the median
int totalLength = m + n;
if (totalLength % 2 == 1) {
// Odd length: The median is the middle element

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


printf("%.5f\n", merged[totalLength / 2]);
} else {
// Even length: The median is the average of the two middle elements
int mid = totalLength / 2;
double median = (merged[mid - 1] + merged[mid]) / 2.0;
printf("%.5f\n", median);
}
}
int main() {
int m, n;
// Read the size and elements of the first array
scanf("%d", &m);
int arr1[m];
for (int i = 0; i < m; i++) {
scanf("%d", &arr1[i]);
}
// Read the size and elements of the second array
scanf("%d", &n);
int arr2[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr2[i]);
}
// Call the function to find the median

Page No: 168


findMedian(arr1, m, arr2, n);
return 0;
}

ID: 247Y1A6790
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
2
13
1
2

2024-2028-CSD-B
2.00000

Test Case - 2

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


2
12
2
34
2.50000

Test Case - 3

User Output
3
568
4
1 9 15 20
8.00000

Test Case - 4

User Output
5
4
3
5

369

4.00000
7.50000

4 6 8 12

12345
3 6 9 12 15

User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 169
Date: 2024-12-
S.No: 76 Exp. Name: Minimum Path Sum

Page No: 170


18

Aim:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom
right, which minimizes the sum of all numbers along its path.

ID: 247Y1A6790
Note: You can only move either down or right at any point in time.

Input Format:
First line of input contains two space separated integers m, n, representing the size of
grid
Next m lines contain n space separated elements of the grid

Output Format:
Print the minimal sum of all numbers along the path

2024-2028-CSD-B
Constraints:
1 <= m, n <= 200
0 <= grid[i][j] <= 200

Example:
Input:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


33
131
151
421

Output:
7

Explanation:
Source Code:

MinimumPathSum.c
The Path with minimum sum is: 1 -> 3 -> 1 -> 1 -> 1 which is equal to 7

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 171
#include <stdio.h>

Page No: 172


int minPathSum(int m, int n, int grid[m][n]) {
int dp[m][n];

// Initialize the starting point


dp[0][0] = grid[0][0];

ID: 247Y1A6790
// Initialize first row (can only come from the left)
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// Initialize first column (can only come from the top)
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// Fill the rest of the dp table
for (int i = 1; i < m; i++) {

2024-2028-CSD-B
for (int j = 1; j < n; j++) {
dp[i][j] = grid[i][j] + (dp[i - 1][j] < dp[i][j - 1] ? dp[i - 1][j] :
dp[i][j -
1]);
}
}
// The bottom-right corner holds the result

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return dp[m - 1][n - 1];
}
int main() {
int m, n;
// Read the size of the grid
scanf("%d %d", &m, &n);

// Create the grid and read its values


int grid[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &grid[i][j]);
}
}
// Call the function to compute the minimum path sum
int result = minPathSum(m, n, grid);
// Print the result
printf("%d\n", result);
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 173


Test Case - 1

User Output
33

ID: 247Y1A6790
131
151
421
7

Test Case - 2

User Output
33

2024-2028-CSD-B
132
473
645
14

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
44
3310
3033
2303
0333
15

Test Case - 4

User Output
43
311
251
155
211
21
10

33

789
456
123
User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 174
Date: 2024-12-
S.No: 77 Exp. Name: Majority Element

Page No: 175


18

Aim:
Given an array arr of size n, return the majority element. The majority element is the
element that appears more than [ n / 2 ] times. You may assume that the majority

ID: 247Y1A6790
element always exists in the array.

Input Format:
First line of input contains an integer n
Second line of input contains n no of space separated elements of the array

Output Format:
Print the majority element of the array

Constraints:

2024-2028-CSD-B
1 <= n <= 5 * 104
0 <= arr[i] <= 109
Source Code:

MajorityElement.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 176


int findMajorityElement(int n, int arr[]) {
int candidate = -1, count = 0;

// Phase 1: Find the candidate


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

ID: 247Y1A6790
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}

// Phase 2: The candidate is guaranteed to be the majority element

2024-2028-CSD-B
return candidate;
}
int main() {
int n;
scanf("%d", &n); // Read the number of elements in the array

int arr[n];

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read the elements of the array
}

int majorityElement = findMajorityElement(n, arr);


printf("%d\n", majorityElement); // Output the majority element

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
3
323
3
Test Case - 2

Page No: 177


User Output
7
2211122
2

ID: 247Y1A6790
Test Case - 3

User Output
8
12112121
1

2024-2028-CSD-B
Test Case - 4

User Output
10
5651585455
5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
7
12 12 12 45 59 12 1
12
Date: 2024-12-
S.No: 78 Exp. Name: Search Insert Position

Page No: 178


18

Aim:
Given a sorted array of distinct integers and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.

ID: 247Y1A6790
Input Format:
First line of input contains an integer n
Second line of input contains n no of space separated elements of the sorted array
Third line of input contains an integer representing the target value

Output Format:
Print the index if the target value is found. If not, print the index where it would be if it
were inserted in order.

2024-2028-CSD-B
Constraints:
1 <= n <= 104
0 <= arr[i] <= 109
Source Code:

SearchInsertPosition.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 179


int searchInsertPosition(int arr[], int n, int target) {
int left = 0, right = n - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

ID: 247Y1A6790
if (arr[mid] == target) {
return mid; // Target found, return the index
} else if (arr[mid] < target) {
left = mid + 1; // Target is on the right side
} else {
right = mid - 1; // Target is on the left side
}
}

// If target is not found, `left` is the insertion point

2024-2028-CSD-B
return left;
}
int main() {
int n;
scanf("%d", &n); // Read the size of the array

int arr[n];

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read the elements of the array
}

int target;
scanf("%d", &target); // Read the target value

int result = searchInsertPosition(arr, n, target);


printf("%d\n", result); // Print the result (index of target or
insertion position)

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
4
1356

Page No: 180


5
2

Test Case - 2

ID: 247Y1A6790
User Output
4
1356
2
1

Test Case - 3

2024-2028-CSD-B
User Output
4
1356
7
4

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
5
13579
9
4

Test Case - 5

User Output
5
13579
8
4
Exp. Name: Count the Negative Date: 2024-12-
S.No: 79

Page No: 181


Numbers 18

Aim:
Given a matrix m × n grid which is sorted in non-increasing order both row-wise and
column-wise, return the number of negative numbers in the grid.

ID: 247Y1A6790
Input Format:
• The first line of input contains two space-separated integers m and n respectively
• Next m lines contain n space-separated integers of the grid in non-increasing
order

Output Format:
• Print the number of negative numbers in the grid

Constraints:

2024-2028-CSD-B
• 1 ≤ m, n ≤ 100

• −100 ≤ grid [i] [j] ≤ 100

Source Code:

CountNegativeNumbers.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 182


int countNegativeNumbers(int m, int n, int grid[m][n]) {
int count = 0;
int row = 0, col =0; // Start from the top-right corner

// Traverse the matrix


for(row=0;row<m;row++) {

ID: 247Y1A6790
for(col=0;col<n;col++){
if (grid[row][col] < 0) {
// If the current element is negative, count all the negative numbers
in this row
count += 1; // All elements in the row to the left are negative
// Move to the next row
}
}
}

2024-2028-CSD-B
return count;
}
int main() {
int m, n;
scanf("%d %d", &m, &n); // Input the number of rows and columns

int grid[m][n];

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// Input the matrix grid
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &grid[i][j]);
}
}

// Call the function to count negative numbers


int result = countNegativeNumbers(m, n, grid);

// Output the result


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

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 183


User Output
44
4 3 2 -1
3 2 1 -1

ID: 247Y1A6790
1 1 -1 -2
-1 -1 -2 -3
8

Test Case - 2

User Output
22

2024-2028-CSD-B
32
10
0

Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
32
10 5
84
3 -2
1

Test Case - 4

User Output
33
15 14 13
8 -10 -15
-4 -16 -18
5
0
22

15 13
63 60
User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 184
Date: 2024-12-
S.No: 80 Exp. Name: Strong Password

Page No: 185


18

Aim:
Louise joined a social networking site to stay in touch with her friends. The signup page
required her to input a name and a password. However, the password must be strong.

ID: 247Y1A6790
The website considers a password to be strong if it satisfies the following criteria:
• Its length is at least 6.
• It contains at least one digit.
• It contains at least one lowercase English character.
• It contains at least one uppercase English character.
• It contains at least one special character. The special characters are: !@#$%^&*()-
+
She typed a random string of length nin the password field but wasn't sure if it was
strong. Given the string she typed, can you find the minimum number of characters she
must add to make her password strong?

2024-2028-CSD-B
Note: Here's the set of types of characters in a form you can paste in your solution:
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"

Input Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The first line contains an integer n, the length of the password.
• The second line contains the password string. Each character is either a
lowercase/uppercase English alphabet, a digit, or a special character.
Constraints:
• 1 ≤ n ≤ 100
• All characters in passwordare in [a-z], [A-Z], [0-9], or [!@#$%^&*()-+ ].

Output Format:
• Returns an integer. i.e., the minimum number of characters to add.

 ample Input:
S
3
Ab1
Sample Output:
3
Explanation:
She can make the password strong by adding3 characters, for example, $hk, turning the
password into Ab1$hk which is strong.2 characters aren't enough since the length must
be at least 6.
Source Code:
password.c

Page No: 186


#include <stdio.h>
#include <ctype.h>
int main() {
int n;
char password[101];
scanf("%d", &n);

ID: 247Y1A6790
scanf("%s", password);
int has_digit = 0, has_lower = 0, has_upper = 0, has_special = 0;
char special_characters[] = "!@#$%^&*()-+";
for (int i = 0; i < n; i++) {
if (isdigit(password[i])) {
has_digit = 1;
} else if (islower(password[i])) {
has_lower = 1;
} else if (isupper(password[i])) {
has_upper = 1;

2024-2028-CSD-B
} else {
for (int j = 0; special_characters[j] != '\0'; j++) {
if (password[i] == special_characters[j]) {
has_special = 1;
break;
}
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
}
int missing_types = 0;
if (!has_digit) missing_types++;
if (!has_lower) missing_types++;
if (!has_upper) missing_types++;
if (!has_special) missing_types++;
int required_length = 6 - n;
int result = missing_types > required_length ? missing_types :
required_length;
printf("%d\n", result);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
3
Ab1

Page No: 187


3

Test Case - 2

ID: 247Y1A6790
User Output
12
#CodeTantra#
1

Test Case - 3

User Output

2024-2028-CSD-B
12
aBcD1234!@#$
0

Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
7
aBcD123
1
Date: 2024-12-
S.No: 81 Exp. Name: Mars Exploration

Page No: 188


18

Aim:
A space explorer’s ship crashed on Mars! In a desperate attempt to call for help, the ship
sends a series of SOS messages to Earth. The original SOS message is a repeating pattern

ID: 247Y1A6790
of the string "SOS". However, cosmic radiation disrupts the signal, causing some
characters to change.

Given the signal received by Earth as a string, s, determine how many characters of the
SOS message have been altered during transmission.

Input Format:
• A single line containing a string s.

Constraints:

2024-2028-CSD-B
• 1 ≤ length of s ≤ 100
• length of s modulo 3 = 0
• s will contain only uppercase English letters, ascii[A-Z].

Output Format:
• Output a single integer, which is the number of letters that have been changed
during transmission.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


How SOS Messages Work:
The original SOS message sent by the ship consists of repeating the string "SOS". For
example:
• If the message length is 6 characters, the expected SOS message would be
"SOSSOS".
• If the message length is 12 characters, it would be "SOSSOSSOSSOS".

 ample Input:
S
SOSSPSSQSSOR

Sample Output:
3

Explanation:
Expected signal: SOSSOSSOSSOS
Recieved signal: SOSSPSSQSSOR
Difference: X X X
The length of the received signal is 12 characters.
Based on this length, the expected SOS message would be "SOSSOSSOSSOSS" (which is
"SOS" repeated 4 times).
Compare the received signal SOSSPSSQSSOR with the expected message
"SOSSOSSOSSOSS":

Page No: 189


• The 4th character in the received signal is 'P', but it should be 'S'.
• The 7th character in the received signal is 'Q', but it should be 'S'.
• The 10th character in the received signal is 'R', but it should be 'S'.
There are 3 positions where the received signal differs from the expected SOS message.
Thus, the number of letters changed during transmission is 3.

ID: 247Y1A6790
Source Code:

letters.c

#include <stdio.h>
#include <string.h>
int main() {
char received[1000];
int altered_count = 0;
scanf("%s", received);
int length = strlen(received);

2024-2028-CSD-B
for (int i = 0; i < length; i++) {
char expected_char = "SOS"[i % 3];
if (received[i] != expected_char) {
altered_count++;
}
}
printf("%d\n", altered_count);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
SOSSOT
1

Test Case - 2

User Output
SOSSPSSQSSOR
3
0
0

SO
User Output
User Output
SOSSOSSOSSOS

Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 190
Date: 2024-12-
S.No: 82 Exp. Name: Happy string.

Page No: 191


18

Aim:
Sarika has a string S with him. Sarika is happy if the string contains a contiguous
substring of length strictly greater than 2 in which all its characters are vowels.

ID: 247Y1A6790
Determine whether Sarika is happy or sad.

Note that, in english alphabet, vowels are a, e, i, o, and u.

Input Format:
• One line of input: a single string,s .
Constraints:
• 3 ≤ |s| ≤ 1000, where |s| is the length of s.
• length of s modulo 3 = 0
• s will only contain lowercase English letters.

2024-2028-CSD-B
Output Format:
• Returns Happy if Sarika is happy, Otherwise, Sad.

Note: This question does not have partial weightages for test cases. All the test cases
must be passed.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

string.c
#include <stdio.h>

Page No: 192


#include <string.h>
int isVowel(char ch) {
// Function to check if a character is a vowel
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u');
}

ID: 247Y1A6790
int main() {
char str[1000]; // Assuming the maximum length of the string is 1000
characters
// Read the input string
scanf("%s", str);
int max_len = 0; // To store the maximum length of contiguous vowels
int current_len = 0; // To track the current length of a contiguous
vowel substring
// Iterate over the string to find the longest contiguous vowel
substring

2024-2028-CSD-B
for (int i = 0; i < strlen(str); i++) {
if (isVowel(str[i])) {
// If the character is a vowel, increase the current length
current_len++;
if (current_len > max_len) {
max_len = current_len;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


} else {
// If the character is not a vowel, reset the current length
current_len = 0;
}
}
// If the maximum length of contiguous vowels is greater than 2,
Sarika is happy
if (max_len > 2) {
printf("Happy\n");
} else {
printf("Sad\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 193


aeiou
Happy

Test Case - 2

ID: 247Y1A6790
User Output
aebcdefghij
Sad

Test Case - 3

User Output
abcdeeafg

2024-2028-CSD-B
Happy

Test Case - 4

User Output
Happy

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Sad
Exp. Name: Find the Index of the First Date: 2024-12-
S.No: 83

Page No: 194


Occurrence in a String. 18

Aim:
Given two strings needle and haystack, return the index of the first occurrence of needle in
haystack, or -1 if needle is not part of haystack.

ID: 247Y1A6790
Input Format:
• The first line should be a input string i.e.,haystack.
• The secondline should be a input string i.e.,needle
Constraints:
• 1 <= haystack.length, needle.length <= 104
• haystack and needle consist of only lowercase English characters.

Output Format:
• Return an integer representing the index.

2024-2028-CSD-B
Source Code:

index.c

#include <stdio.h>
#include <string.h>
int strStr(char *haystack, char *needle) {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// Use strstr to find the first occurrence of needle in haystack
char *ptr = strstr(haystack, needle);

// If the needle is found, return the index, else return -1


if (ptr != NULL) {
return ptr - haystack; // Return the index of the firstoccurrence
} else {
return -1; // If needle is not found in haystack
}
}
int main() {
char haystack[10000], needle[10000];

// Read input strings


scanf("%s", haystack);
scanf("%s", needle);

// Call the strStr function and print the result


printf("%d\n", strStr(haystack, needle));

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 195


Test Case - 1

User Output
sadbutsad

ID: 247Y1A6790
sad
0

Test Case - 2

User Output
short
longstrong
-1

2024-2028-CSD-B
Test Case - 3

User Output
abracadabra
ab

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


0

Test Case - 4

User Output
AbCdEfGh
cd
-1
Date: 2024-12-
S.No: 84 Exp. Name: Length of Last Word

Page No: 196


18

Aim:
Given a string s consisting of words and spaces, return the length of the last word in the
string. A word is a maximalsubstringconsisting of non-space characters only.

ID: 247Y1A6790
Input Format:
• The first line should be a input string i.e.,s.

Constraints:
• 1 <= s.length <= 104
• s consists of only English letters and spaces ' '.
• There will be at least one word in s.

Output Format:

2024-2028-CSD-B
• Return an integer representing the length of last word.
Source Code:

length.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 197


#include <string.h>
int lengthOfLastWord(char *s) {
int length = 0;
int i = strlen(s) - 1;

// Skip any trailing spaces

ID: 247Y1A6790
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}

2024-2028-CSD-B
int main() {
char str[10000]; // assuming the maximum length of string is 10000
// Read the input string
fgets(str, sizeof(str), stdin);

// Call the function to get the length of the last word


printf("%d\n", lengthOfLastWord(str)-1);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
hello world
5

Test Case - 2

User Output
luffy is still joyboy
6
8
10
CodeTantra

User Output
User Output

C programming language
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 198
Date: 2024-12-
S.No: 85 Exp. Name: Reverse Vowels of a String

Page No: 199


18

Aim:
Given a string s, reverse only all the vowels in the string and return it. The vowels are
a, e, i, o and u, and they can appear in both lower and upper cases, more than once.

ID: 247Y1A6790
Input Format:
• The first line should be a input string i.e.,s.

Constraints:
• 1 <= s.length <= 3 * 105
• s consist of English alphabets contains both upper and lower case

Output Format:
• Return a reverse string.

2024-2028-CSD-B
Source Code:

reverse.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 200


#include <ctype.h>
#include <string.h>
// Helper function to check if a character is a vowel
int isVowel(char c) {
char vowels[] = "aeiouAEIOU";
for (int i = 0; vowels[i] != '\0'; i++) {

ID: 247Y1A6790
if (c == vowels[i]) {
return 1; // It is a vowel
}
}
return 0; // It is not a vowel
}
void reverseVowels(char *s) {
int left = 0;
int right = strlen(s) - 1;

2024-2028-CSD-B
while (left < right) {
// Find the next vowel from the left
while (left < right && !isVowel(s[left])) {
left++;
}

// Find the next vowel from the right

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


while (left < right && !isVowel(s[right])) {
right--;
}

// If both are vowels, swap them


if (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
int main() {
char s[300001]; // Max length 3 * 10^5

// Read input string


fgets(s, sizeof(s), stdin); s[strcspn(s, "\n")] = 0;

// Reverse the vowels in the string


reverseVowels(s);
Page No: 201
// Print the modified string
printf("%s\n", s);

return 0;
}

ID: 247Y1A6790
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
hello
holle

2024-2028-CSD-B
Test Case - 2

User Output
CodeTantra
CadaTentro

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
CadaTentro
CodeTantra

Test Case - 4

User Output
ABCabc
aBCAbc

Test Case - 5

User Output
decision
Date: 2024-12-
S.No: 86 Exp. Name: Palindromic String

Page No: 202


18

Aim:
You have been given a String s. You need to find and print whether this string is a
palindrome or not.

ID: 247Y1A6790
Input Format:
• The first line should contain the input string s.

Output Format:
• Return "YES" if the input string is a palindrome, "NO"Otherwise.
Source Code:

palindrome.c

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
#include <stdio.h>

Page No: 203


#include <string.h>
int main() {
char s[1000]; // Assume the string length is not greater than 1000
characters

// Read the input string

ID: 247Y1A6790
fgets(s, sizeof(s), stdin);

// Remove the newline character if present (from fgets)


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

int left = 0;
int right = strlen(s) - 1;

// Check for palindrome by comparing characters from both ends


while (left < right) {

2024-2028-CSD-B
if (s[left] != s[right]) {
printf("NO\n");
return 0; // Exit as soon as we find a mismatch
}
left++;
right--;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// If no mismatches were found, it is a palindrome
printf("YES\n");

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
madam
YES

Test Case - 2

User Output
NO
NO
YES
racecar

panama

palindrome
User Output
User Output

Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 204
Date: 2024-12-
S.No: 88 Exp. Name: Trimor Love

Page No: 205


18

Aim:
Trimor loves codetantra. That's why he has a string s having length 10 made containing
only lowercase Latin letters. Trimor wants to know how many indices string s differs from

ID: 247Y1A6790
the string "codetantra".

For example string s="codemantra" differs from "codetantra" in 1indice(s), shown in bold.

Help Trimor by finding the number of indices where string s differs from "codetantra".

Note that you can't reorder the characters in the string s.

Input Format:
Single line of input contains a string s.

2024-2028-CSD-B
Output Format:
If the length of string s is not equal to 10, then print -1, otherwise print the number of
indices where string s differs.

Constraints:
Input string s must be of length 10 only

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Source Code:

CharDiffer.c
#include <stdio.h>

Page No: 206


#include <string.h>
int main() {
// Read input string s
char s[11]; // One extra space for the null terminator
scanf("%s", s);

ID: 247Y1A6790
// Target string
const char target[] = "codetantra";

// Check if the length of the string is not 10


if (strlen(s) != 10) {
printf("-1\n");
return 0;
}
// Count the number of differing indices
int count = 0;

2024-2028-CSD-B
for (int i = 0; i < 10; i++) {
if (s[i] != target[i]) {
count++;
}
}
// Print the result
printf("%d\n", count);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
codemantra
1

Test Case - 2

User Output
coursecode
8
9
0
6

questionss
codetantra
codecourse

User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 207
Date: 2024-12-
S.No: 89 Exp. Name: Length of the Ladder

Page No: 208


18

Aim:
A man needs to reach a window which is positioned above the ground at some height H
(in feet). There is some distance D (in feet) between the foot of the ladder and the wall.

ID: 247Y1A6790
The man wants to know how long the ladder should be to reach the window safely.
Write a C program to help the man know the length of the ladder.

Input Format:
• First line of input contains an integer H representing the height of the window.
• Second line of input contains an integer D representing the distance between the
foot of the ladder and the wall.

Output Format:
• The length of the ladder required, rounded to two decimal places.

2024-2028-CSD-B
Constraints:
• 1 <= H, D <= 104
Source Code:

LengthOfLadder.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>
#include <math.h>
int main() {
// Declare variables to store the height and distance
int H, D;

// Read the inputs: height of the window (H) and distance from the
wall (D)
scanf("%d", &H);
scanf("%d", &D);

// Calculate the length of the ladder using Pythagorean theorem


double L = sqrt(H * H + D * D);

// Print the length of the ladder rounded to two decimal places


printf("%.2f\n", L);

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 209


Test Case - 1

User Output
40

ID: 247Y1A6790
9
41.00

Test Case - 2

User Output
15
10
18.03

2024-2028-CSD-B
Test Case - 3

User Output
10
10

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


14.14

Test Case - 4

User Output
15
5
15.81

Test Case - 5

User Output
10
15
18.03
Date: 2024-12-
S.No: 90 Exp. Name: Anagram Check

Page No: 210


18

Aim:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.

ID: 247Y1A6790
An Anagram is a word or phrase formed by rearranging the letters of a different word or
phrase, typically using all the original letters exactly once.

Input Format:
Single line of input contains two space separated strings representing s and t

Output Format:
Print True if the string t is an anagram of string s, otherwise print False.

Constraints:

2024-2028-CSD-B
1 <= s.length, t.length <= 5 * 104
s and t consists of lowercase English letters only
Source Code:

AnagramCheck.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 211


#include <string.h>
#define MAX_CHAR 26 // Since the string consists of only
lowercaseletters
// Function to check if two strings are anagrams
int areAnagrams(char *s, char *t) {
// If lengths are different, they cannot be anagrams

ID: 247Y1A6790
if (strlen(s) != strlen(t)) {
return 0; // False
}

// Create an array to count the frequency of characters


int freq[2][MAX_CHAR] = {0}; // Two frequency arrays for s and t

// Count the frequency of characters in both strings


for (int i = 0; s[i] != '\0'; i++) {
freq[0][s[i] - 'a']++;

2024-2028-CSD-B
freq[1][t[i] - 'a']++;
}

// Compare frequency arrays


for (int i = 0; i < MAX_CHAR; i++) {
if (freq[0][i] != freq[1][i]) {
return 0; // False

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
}

return 1; // True
}
int main() {
char s[50005], t[50005];

// Read input strings


scanf("%s %s", s, t);

// Check if t is an anagram of s
if (areAnagrams(s, t)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 212


Test Case - 1

User Output
anagram nagaram

ID: 247Y1A6790
True

Test Case - 2

User Output
rat car
False

Test Case - 3

2024-2028-CSD-B
User Output
carrace racecar
True

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
eat ate
True

Test Case - 5

User Output
eat bat
False
Exp. Name: First Unique Character in a Date: 2024-12-
S.No: 91

Page No: 213


String 18

Aim:
Given a string s, find the first non-repeating character in it and return its index. If it does
not exist, return -1.

ID: 247Y1A6790
Input Format:
Single line of input contains a string s

Output Format:
Print the index of the first non-repeating character, if it does not exist, print -1

Constraints:
1 <= s.length <= 105
string s consists of only lowercase English letters

2024-2028-CSD-B
Source Code:

UniqueCharacterIndex.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 214


#include <string.h>
#define MAX_CHAR 26 // Since the string consists of only lowercase
letters
int firstUniqChar(char *s) {
int freq[MAX_CHAR] = {0}; // Array to store the frequency of each
character

ID: 247Y1A6790
// Count the frequency of each character in the string
for (int i = 0; s[i] != '\0'; i++) {
freq[s[i] - 'a']++;
}

// Find the first character with frequency 1


for (int i = 0; s[i] != '\0'; i++) {
if (freq[s[i] - 'a'] == 1) {
return i; // Return the index of the first non-repeating character

2024-2028-CSD-B
}
}

return -1; // If no non-repeating character is found, return -1


}
int main() {
char s[100001]; // Declare a string of size 100001 (to handle up

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


to10^5 characters)

// Read the input string


scanf("%s", s);

// Call the function to find the index of the first non-repeating


character
int result = firstUniqChar(s);

// Output the result


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

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 215


aaaaaa
-1

Test Case - 2

ID: 247Y1A6790
User Output
abcdefghijklmnopqrstuvwxyza
1

Test Case - 3

User Output
codetantra

2024-2028-CSD-B
0

Test Case - 4

User Output
proper

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


2

Test Case - 5

User Output
abababacd
7
Date: 2024-12-
S.No: 92 Exp. Name: Return of the Robot

Page No: 216


18

Aim:
A robot starts at the origin (0, 0) on a 2D plane. It is given a sequence of moves
represented by the string "moves". Each move is represented by 'R' (right), 'L' (left), 'U'

ID: 247Y1A6790
(up), or 'D' (down). The task is to determine if the robot returns to the origin after
completing all the moves. The robot's direction is irrelevant, and all moves have the same
magnitude. Return true if the robot ends up at the origin, and false otherwise.

Input Format:
Single line of input contains a string representing the moves of the robot

Output Format:
Print True if the robots returns to the origin after completing all the moves, otherwise
print False

2024-2028-CSD-B
Constraints:
1 <= moves.length <= 2 * 104
moves only contains the characters 'U', 'D', 'L' and 'R'
Source Code:

RobotReturns.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 217


#include <stdbool.h>
bool judgeCircle(char *moves) {
// Initialize the robot's starting position at the origin (0, 0)
int x = 0, y = 0;
// Iterate through each move in the string
for (int i = 0; moves[i] != '\0'; i++) {

ID: 247Y1A6790
if (moves[i] == 'R') {
x++; // Move right, increase x
} else if (moves[i] == 'L') {
x--; // Move left, decrease x
} else if (moves[i] == 'U') {
y++; // Move up, increase y
} else if (moves[i] == 'D') {
y--; // Move down, decrease y
}
}

2024-2028-CSD-B
// If the robot is back at the origin, return true
return x == 0 && y == 0;
}
int main() {
char moves[20001]; // Assuming the max length of moves is 2 * 10^4
// Read the input string representing the moves
scanf("%s", moves);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// Call the function to check if the robot returns to the origin
if (judgeCircle(moves)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
UD
True

Test Case - 2
User Output

Page No: 218


LL
False

Test Case - 3

ID: 247Y1A6790
User Output
URDL
True

Test Case - 4

User Output
UUDRL

2024-2028-CSD-B
False

Test Case - 5

User Output
UDUD

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


True
Date: 2024-12-
S.No: 93 Exp. Name: Frustrated Faculty

Page No: 219


18

Aim:
Chandini is a bad student. Once his teacher asked her to print the reverse of a given
string. She took three hours to solve it. The teacher got agitated at Chandini and asked

ID: 247Y1A6790
you the same question. Can you solve it?

Input Format:
Single line of input contains a string

Output Format:
Print the reverse of the given string

Constraints:
1 <= string length <= 50

2024-2028-CSD-B
Source Code:

StringReverse.c

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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


char str[51]; // Array to hold the string (size 51 to account for the
null terminator)

// Read the input string


scanf("%s", str);

int len = strlen(str); // Get the length of the string

// Reverse the string by swapping characters


for (int i = 0; i < len / 2; i++) {
// Swap the characters at positions i and len - 1 - i
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}

// Print the reversed string


printf("%s\n", str);

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 220


Test Case - 1

User Output
chandini

ID: 247Y1A6790
inidnahc

Test Case - 2

User Output
reverse
esrever

Test Case - 3

2024-2028-CSD-B
User Output
string
gnirts

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
faculty
ytlucaf

Test Case - 5

User Output
solution
noitulos
Date: 2024-12-
S.No: 94 Exp. Name: Repeated String

Page No: 221


18

Aim:
There is a string, S, of lowercase English letters that is repeated infinitely many times.
Given an integer, N, find and print the number of letter a's in the firstN letters of the

ID: 247Y1A6790
infinite string.

Input Format:
• First line of input contains the string S
• Second line of input contains the integer N

Output Format:
• Print the frequency of letter "a" in the substring

Constraints:

2024-2028-CSD-B
• 1 <= string length <= 100
• 1 <= n <= 1012

Example:
string = 'abaca'
n = 10
The substring we consider will be abacaabaca, the first 10 characters of the infinite string.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


There are 6 occurrences of a in the substring
Source Code:

RepeatedString.c
#include <stdio.h>

Page No: 222


#include <string.h>
int main() {
char S[101]; // The string S with a maximum length of 100
long long N; // The integer N can be as large as 10^12

// Reading the input

ID: 247Y1A6790
scanf("%s", S);
scanf("%lld", &N);

// Calculate the length of the string S


int len = strlen(S);

// Count how many 'a's are in the string S


int count_a_in_S = 0;
for (int i = 0; i < len; i++) {
if (S[i] == 'a') {

2024-2028-CSD-B
count_a_in_S++;
}
}

// Determine how many full repeats of S fit into N characters


long long full_repeats = N / len;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// Count how many 'a's in the full repeats
long long total_a_count = full_repeats * count_a_in_S;

// Consider the remaining characters in the partial repeat


long long remaining_chars = N % len;
for (int i = 0; i < remaining_chars; i++) {
if (S[i] == 'a') {
total_a_count++;
}
}

// Print the result


printf("%lld\n", total_a_count);

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 223


User Output
abaca
10
6

ID: 247Y1A6790
Test Case - 2

User Output
seedof
15
0

2024-2028-CSD-B
Test Case - 3

User Output
avacado
50
22

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
propose
50
0

Test Case - 5

User Output
parameter
90
20
Date: 2024-12-
S.No: 95 Exp. Name: Climbing Stairs

Page No: 224


18

Aim:
You are climbing a staircase. It takes n steps to reach the top.

ID: 247Y1A6790
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to
the top?

Constraints:
•1≤n ≤ 45

Input Format:
• The only line containsan integern.

Output Format:

2024-2028-CSD-B
• Return the integer which results in calculating the no.of distinct ways to climb a
staircase with n steps.
Source Code:

step.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 225


int climbStairs(int n) {
if (n == 1) return 1; // If there's only one step, only one way reach
the top.

int first = 1, second = 2; // base cases: first = dp[0], second =


dp[1]

ID: 247Y1A6790
for (int i = 3; i <= n; i++) {
int current = first + second; // dp[i] = dp[i-1] + dp[i-2]
first = second; // move the second value to first
second = current; // move the current value to second
}

return second; // return dp[n]


}
int main() {

2024-2028-CSD-B
int n;
// Input the number of steps
scanf("%d", &n);

// Output the result


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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
2

Test Case - 2

User Output
3
3
8
5

5
4

User Output
User Output

Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 226
Date: 2024-12-
S.No: 97 Exp. Name: Power of Four

Page No: 227


18

Aim:
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4

ID: 247Y1A6790
x

.
Constraints:
• −2 ≤ n ≤ 2 − 1
31 31

Input Format:
• The only line containsan integern

Output Format:
• Return true if n is a power of four. Otherwise, false.
Source Code:

2024-2028-CSD-B
power.c
#include <stdio.h>
#include <stdbool.h>
bool isPowerOfFour(int n) {
// A number is a power of 4 if:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


// 1. It is a positive number
// 2. It is a power of 2 (i.e., only one bit is set)
// 3. The set bit is at an even position (n % 3 == 1)

return (n > 0) && (n & (n - 1)) == 0 && (n % 3 == 1);


}
int main() {
int n;

// Input the number


scanf("%d", &n);

// Output the result


if (isPowerOfFour(n)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 228


Test Case - 1

User Output
16

ID: 247Y1A6790
true

Test Case - 2

User Output
5
false

Test Case - 3

2024-2028-CSD-B
User Output
1
true

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
0
false
Date: 2024-12-
S.No: 98 Exp. Name: Factorial using Recursion

Page No: 229


18

Aim:
You are given an integer N . You need to print N ! - the factorial of N .
.

ID: 247Y1A6790
Constraints:
• 1 ≤ T ≤ 10
• 0 ≤ N ≤ 20

Input Format:
• The first line of the input contains a single integerT denoting the number of test
cases. The description ofT test cases follows.
• The first and only line of each test case contains a single integerN

Output Format:

2024-2028-CSD-B
• For each test case print a single line containing a single integerN !
Source Code:

factorial.c

#include <stdio.h>
// Function to compute the factorial of a number

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


unsigned long long factorial(int n) {
if(n==1)
return 1;
else
return factorial(n-1)*n;

}
int main() {
int t; // Number of test cases
scanf("%d", &t); // Read number of test cases

while (t--) {
int n; // The number for which we need to compute factorial
scanf("%d", &n); // Read the integer n

// Call the factorial function and print the result


printf("%llu\n", factorial(n));
}

return 0;
}
Execution Results - All test cases have succeeded!

Page No: 230


Test Case - 1

User Output
2

ID: 247Y1A6790
12
1
2

Test Case - 2

User Output
3
362

2024-2028-CSD-B
6
720
2

Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
3
321
6
2
1

Test Case - 4

User Output
2
46
24
720
Date: 2024-12-
S.No: 99 Exp. Name: Fibonacci Number

Page No: 231


18

Aim:
The Fibonacci numbers, commonly denoted F (n) form a sequence, called the Fibonacci
sequence, such that each number is the sum of the two preceding ones, starting from 0

ID: 247Y1A6790
and 1.That is,

F (0) = 0, F (1) = 1

F (n) = F (n − 1) + F (n − 2), f or n > 1

Given n, calculate F (n).

Constraints:
•0≤n ≤ 30

2024-2028-CSD-B
Input Format:
• The first line of the input contains a single integern.

Output Format:
• Return a single integerafter calculating F (n).
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


fibonacci.c
#include <stdio.h>

Page No: 232


// Function to calculate the nth Fibonacci number
unsigned long long fibonacci(int n) {
// Handle the base cases
if (n == 0) return 0;
if (n == 1) return 1;
unsigned long long a = 0, b = 1; // F(0) = 0, F(1) = 1

ID: 247Y1A6790
unsigned long long result = 0;
// Calculate Fibonacci numbers iteratively
for (int i = 2; i <= n; i++) {
result = a + b;
a = b; // Update a to the previous Fibonacci number
b = result; // Update b to the current Fibonacci number
}
return result;
}
int main() {

2024-2028-CSD-B
int n;
scanf("%d", &n); // Read the input n
// Call the Fibonacci function and print the result
printf("%llu\n", fibonacci(n));
return 0;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
3
2

Test Case - 2

User Output
4
3

Test Case - 3
5
5

55
10
User Output
Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 233
Date: 2024-12-
S.No: 100 Exp. Name: Best Divisor

Page No: 234


18

Aim:
Kristen loves playing with and comparing numbers. She thinks that if she takes two
different positive numbers, the one whose digits sum to a larger number is better than

ID: 247Y1A6790
the other. If the sum of digits is equal for both numbers, then she thinks the smaller
number is better.

For example, Kristen thinks that 13 is better than 31 and that 12 is better than 11. Given
an integer n, can you find the divisor of n that Kristin will consider to be the best?

Constraints:
•0<n ≤ 10
5

Input Format:

2024-2028-CSD-B
• The first line of the input contains a single integern.

Output Format:
• Print an integer denoting the best divisor of n.
Source Code:

Divisor.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 235


// Function to calculate the sum of digits of a number
int sum_of_digits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;

ID: 247Y1A6790
}
return sum;
}
int main() {
int n;
scanf("%d", &n); // Read the input integer n
int best_divisor = -1; // To store the best divisor
int max_digit_sum = -1; // To track the maximum sum of digits
// Find all divisors of n
for (int i = 1; i * i <= n; i++) {

2024-2028-CSD-B
if (n % i == 0) { // i is a divisor
// Check the sum of digits of i
int sum_i = sum_of_digits(i);
if (sum_i > max_digit_sum || (sum_i == max_digit_sum && i <
best_divisor)) {
max_digit_sum = sum_i;
best_divisor = i;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
// Check the complement divisor n / i
if (i != n / i) { // Avoid counting the square root twice
int sum_complement = sum_of_digits(n / i);
if (sum_complement > max_digit_sum || (sum_complement
== max_digit_sum && n / i < best_divisor)) {
max_digit_sum = sum_complement;
best_divisor = n / i;
}
}
}
}
// Output the best divisor
printf("%d\n", best_divisor);
return 0;
}

Execution Results - All test cases have succeeded!


1
6

28
13

28
13
12

User Output
User Output
User Output
User Output

Test Case - 4
Test Case - 3
Test Case - 2
Test Case - 1

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 236
Date: 2024-12-
S.No: 101 Exp. Name: Perfect Number or Not

Page No: 237


18

Aim:
A perfect number is a positive integer that is equal to the sum of its positive divisors,
excluding the number itself. A divisor of an integer x is an integer that can divide x

ID: 247Y1A6790
evenly.

Given an integer n, return True if n is a perfect number, otherwise return False.

Input Format:
A single line of input contains an integer n

Output Format:
Print True if n is a perfect number, otherwise return False.

2024-2028-CSD-B
Constraints:
1 <= n <= 108

Note: This question does not contains weghtage for test cases. All test cases must be
passed.
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


PerfectNumber.c
#include <stdio.h>

Page No: 238


#include <math.h>
// Function to check if a number is a perfect number
int isPerfectNumber(int n) {
if (n <= 1) {
return 0; // 1 is not a perfect number, and numbers less than 1 don't
make sense for this problem

ID: 247Y1A6790
}
int sum = 1; // 1 is always a divisor
int sqrt_n = sqrt(n);
// Loop from 2 to sqrt(n) to find divisors
for (int i = 2; i <= sqrt_n; i++) {
if (n % i == 0) {
sum += i; // Add divisor i
if (i != n / i) { // Avoid adding the square root twice if n is a
perfect square
sum += n / i; // Add the complement divisor n / i

2024-2028-CSD-B
}
}
}
// Return true if sum of divisors equals n
return sum == n;
}
int main() {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int n;
scanf("%d", &n); // Read input
// Check if n is a perfect number
if (isPerfectNumber(n)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
28
True
Test Case - 2

Page No: 239


User Output
7
False

ID: 247Y1A6790
Test Case - 3

User Output
6
True

Test Case - 4

2024-2028-CSD-B
User Output
45
False

Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
63
False
Date: 2024-12-
S.No: 102 Exp. Name: Adding the Digits

Page No: 240


18

Aim:
Given an integer num, repeatedly add all its digits until the result has only one digit, and
return it.

ID: 247Y1A6790
Input Format:
Single line of input contains an integer num

Output Format:
Print the result after adding all the digits till it becomes a single digit

Constraints:
0 <= num <= 231 - 1
Source Code:

2024-2028-CSD-B
AddDigits.c

#include <stdio.h>
int addDigits(int num) {
if (num == 0) {
return 0;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
if (num % 9 == 0) {
return 9;
}
return num % 9;
}
int main() {
int num;
scanf("%d", &num); // Read the input number
printf("%d\n", addDigits(num)); // Output the result
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
38
2

Page No: 241


Test Case - 2

User Output
154

ID: 247Y1A6790
1

Test Case - 3

User Output
153
9

2024-2028-CSD-B
Test Case - 4

User Output
321456
3

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 5

User Output
132456
3
Date: 2024-12-
S.No: 103 Exp. Name: Something for Profit

Page No: 242


18

Aim:
A friend of yours bought a used pressure cooker for an initial cost of X rupees. Later, she
sold it to another friend for Y rupees. However, she regretted the sale and decided to buy

ID: 247Y1A6790
it back by offering Z rupees. After having bought it again, she felt that she didn't really
need the cooker and sold it at an auction for W rupees. Can you determine whether she
made a profit or incurred a loss, and if so, how much?
Write a C program that takes the values of X, Y, Z, and W as input and calculates the
profit or loss.

Input Format:
• First line contains two space separated integers X, Y representing the initial cost
and the first sale price
• Second line contains two space separated integers Z, W representing the buy-back

2024-2028-CSD-B
cost and the auction sell price

Output Format:
• Print the amount if she got any profit (Positive numbers) or loss (negative
numbers) or if no gain of profit or loss, print 0 (zero)
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


ProfitOrLoss.c

#include <stdio.h>
int main() {
int X, Y, Z, W; // Declare variables to store the values of X, Y, Z,
and W
// Reading the input values
scanf("%d %d", &X, &Y); // First line: X and Y
scanf("%d %d", &Z, &W); // Second line: Z and W
// Calculate the total spent and total earned
int totalSpent = X + Z;
int totalEarned = Y + W;
// Calculate the net profit or loss
int profitOrLoss = totalEarned - totalSpent;
// Output the result based on the profit or loss
printf("%d\n", profitOrLoss);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 243


User Output
60 70
80 90
20

ID: 247Y1A6790
Test Case - 2

User Output
90 70
80 60
-40

2024-2028-CSD-B
Test Case - 3

User Output
40 50
60 50
0

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
150 200
250 250
50

Test Case - 5

User Output
80 50
60 50
-40
Date: 2024-12-
S.No: 104 Exp. Name: Reverse an Integer

Page No: 244


18

Aim:
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the
value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

ID: 247Y1A6790
Input Format:
Single line of input contains an integer x

Output Format:
Print the reversed integer of x

Constraints:
-231 <= x <= 231 - 1
Source Code:

2024-2028-CSD-B
ReverseAnInteger.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 245


#include <limits.h>
int reverse(int x) {
int reversed = 0;
// Handle negative number separately
while (x != 0) {
int digit = x % 10;

ID: 247Y1A6790
x /= 10;
// Check if reversing will cause overflow
if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 &&
digit > 7)) {
return 0; // Overflow case
}
if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 &&
digit < -8)) {
return 0; // Underflow case
}

2024-2028-CSD-B
reversed = reversed * 10 + digit;
}
return reversed;
}
int main() {
int x;
// Reading the input integer

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


scanf("%d", &x);
// Print the reversed integer
printf("%d\n", reverse(x));
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1534236469
0

Test Case - 2

User Output
123
321

Page No: 246


Test Case - 3

User Output
-5689

ID: 247Y1A6790
-9865

Test Case - 4

User Output
32154869
96845123

2024-2028-CSD-B
Test Case - 5

User Output
2147483649
0

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Date: 2024-12-
S.No: 105 Exp. Name: Move Zeroes

Page No: 247


18

Aim:
Given an integer array nums, move all 0's to the end of it while maintaining the relative
order of the non-zero elements.

ID: 247Y1A6790
Note that you must do this in-place without making a copy of the array.

Input Format:
• First line of input contains an integer N representing the size of array
• Second line contains N space separated integers representing the array elements

Output Format:
• Print the array after moving all the zero elements to the end

2024-2028-CSD-B
Constraints:
• 1 <= nums.length <= 104
• -231 <= nums[i] <= 231 - 1
Source Code:

MoveZeroesToEnd.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>

Page No: 248


void moveZeroes(int* nums, int n) {
int j = 0; // Pointer to track the position for the next non-zero
element
// Traverse the array
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {

ID: 247Y1A6790
// Swap the non-zero element with the element at position j
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++; // Increment the position for the next non-zero element
}
}
}
int main() {
int n;

2024-2028-CSD-B
// Read the size of the array
scanf("%d", &n);

int nums[n];

// Read the array elements

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
// Move zeroes to the end
moveZeroes(nums, n);

// Print the array after moving zeros


for (int i = 0; i < n; i++) {
printf("%d ", nums[i]);
}
printf("\n");
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
0 1 0 3 12

Page No: 249


1 3 12 0 0

Test Case - 2

ID: 247Y1A6790
User Output
5
12030
1 2 3 0 0

Test Case - 3

User Output

2024-2028-CSD-B
1
0
0

Test Case - 4

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
10
0102030405
1 2 3 4 5 0 0 0 0 0

Test Case - 5

User Output
6
000010
1 0 0 0 0 0
Date: 2024-12-
S.No: 106 Exp. Name: Number of 1 Bits

Page No: 250


18

Aim:
Write a program that takes the binary representation of an unsigned integer and returns
the number of '1' bits it has (also known as the Hamming weight).

ID: 247Y1A6790
Input Format:
Single line of input contains the required binary string

Output Format:
Print the total no of '1' bits present in the given binary string

Constraints:
The input must be a binary string of length 32
Source Code:

2024-2028-CSD-B
NoOfOneBits.c

#include <stdio.h>
int main() {
char binary[33]; // Array to store the binary string, max length 32
plus null terminator.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int count = 0; // Variable to store the count of '1' bits.

// Read the input binary string (length should be 32)


scanf("%32s", binary);

// Traverse the binary string and count '1' bits


for (int i = 0; i < 32; i++) {
if (binary[i] == '1') {
count++; // Increment count if '1' is encountered.
}
}
// Print the count of '1' bits
printf("%d\n", count);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 251


00000000000000000000000000001011
3

Test Case - 2

ID: 247Y1A6790
User Output
00000000000000000000000010000000
1

Test Case - 3

User Output
11111111111111111111111111111101

2024-2028-CSD-B
31

Test Case - 4

User Output
00000011110000111000011001100110

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


13

Test Case - 5

User Output
00000000000000000000000000000000
0
Date: 2024-12-
S.No: 107 Exp. Name: Cut the Bread

Page No: 252


18

Aim:
Martha is interviewing at Subway. One of the rounds of the interview requires her to cut a
bread of size L * Binto smaller identical pieces such that each piece is a square having

ID: 247Y1A6790
maximum possible side length with no left over piece of bread.

Input Format:
Single line of input contains two space separated integers L and B representing the
length and breadth of the bread

Output Format:
Print an integer that denotes the number of squares of maximum size, when the bread is
cut as per the given condition.

2024-2028-CSD-B
Constraints:
1 <= L, B <= 1000
Source Code:

CutTheBread.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 253


// Function to compute the GCD of two numbers
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;

ID: 247Y1A6790
}
return a;
}
int main() {
int L, B;

// Read the input values for L and B


scanf("%d %d", &L, &B);

// Calculate the GCD of L and B

2024-2028-CSD-B
int side_length = gcd(L, B);

// Calculate the number of squares


int num_squares = (L * B) / (side_length * side_length);

// Print the number of squares


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

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
22
1

Test Case - 2

User Output
69
6
2
1

40
44

50 80
12 24

User Output
User Output
User Output

Test Case - 5
Test Case - 4
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 254
Date: 2024-12-
S.No: 108 Exp. Name: Points on a Line

Page No: 255


18

Aim:
Given ntwo-dimensional points in space, determine whether they lie on some vertical or
horizontal line. If yes, print YES; otherwise, print NO.

ID: 247Y1A6790
Input Format:
• The first line contains a single positive integer, n, denoting the number of points.
• Next n lines containstwo space-separated integers detailing the respective values
ofandxi and yi (i.e., the coordinates of the ithpoint).

Output Format:
• Print YES if all the points lie on some vertical or horizontal line, otherwise print NO

Constraints:

2024-2028-CSD-B
2 <= n <= 10
-10 <= xi, yi <= 10
Source Code:

PointsOnALine.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include <stdio.h>

Page No: 256


int main() {
int n;
scanf("%d", &n); // Read the number of points
int x, y;
int first_x, first_y;

ID: 247Y1A6790
// Read the first point's coordinates
scanf("%d %d", &first_x, &first_y);

int is_vertical = 1; // Flag for checking if all x are the same


int is_horizontal = 1; // Flag for checking if all y are the same
// Loop through the rest of the points
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y); // Read each point's coordinates

if (x != first_x) {

2024-2028-CSD-B
is_vertical = 0; // If x is not the same as the first x,it's not a
vertical line
}
if (y != first_y) {
is_horizontal = 0; // If y is not the same as the first y,it's not a
horizontal line
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
// If either the x-coordinates are the same or the y-coordinates are
the same for all points, print YES
if (is_vertical || is_horizontal) {
printf("YES\n");
} else {
printf("NO\n");
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
01
02
03
04

Page No: 257


05
YES

Test Case - 2

ID: 247Y1A6790
User Output
5
01
02
13
04
05

2024-2028-CSD-B
NO

Test Case - 3

User Output
5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


10
20
30
40
50
YES

Test Case - 4

User Output
5
10
20
31
40
50
NO
6

NO
59
48
37
26
15

10 10
User Output
Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 258
Exp. Name: Department-wise Salary
Date: 2025-01-

Page No: 259


S.No: 109 Expenditure and Top-performing
02
department.

Aim:

ID: 247Y1A6790
You are building a payroll system for a company with multiple departments. Design a
program using structures that store employee details such as name, employee ID, and
salary. Implement an array of structures to store employee records for each department.
Calculate the total salary expenditure for each department and display it. Additionally,
identify the department with the highest salary expenditure and acknowledge it as the
top-performing department.

Structures:
Employee Structure:
• Name: A string to store the employee's name (up to 50 characters).
• Employee ID: An integer to store the unique ID of the employee.

2024-2028-CSD-B
• Salary: A floating-point number to store the employee's salary.
Department Structure:
• Name: A string to store the department's name (up to 50 characters).
• Employees: An array of Employee structures to store the details of each
employee in the department.
• Number of Employees: An integer to store the count of employees in the

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


department.

Input Format:
1. The first line should contain an integer n, representing the number of departments.
2. For each department (repeat n times):
• Read the department name (a string).
• Read an integer m, which indicates the number of employees in that department.
• For each employee (repeat m times):
• (a) Read the employee name (a string).
• (b) Read the employee ID (an integer).
• (c) Read the employee salary (a floating-point number).

Output Format:
• For each department, print the department name followed by the total salary
expenditure, formatted to two decimal places.
• Finally, print the name of the top-performing department, which has the highest
total salary expenditure.
Source Code:

Salary.c
#include<stdio.h>

Page No: 260


#include<string.h>
#define MAX_DEPARTMENTS 10
#define MAX_EMPLOYEES 50
#define MAX_NAME_LENGTH 50
struct Employee{
char name[MAX_NAME_LENGTH];

ID: 247Y1A6790
int emp_id;
float salary;
};
struct Department{
char name[MAX_NAME_LENGTH];
struct Employee employees[MAX_EMPLOYEES];
int num_employees;
};
float calculate_total_salary(struct Department dept){
float total_salary = 0.0;int i;

2024-2028-CSD-B
for ( i= 0; i < dept.num_employees; i++) {
total_salary += dept.employees[i].salary;
}
return total_salary;
}
int main(){
int num_departments,i,j;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


struct Department departments[MAX_DEPARTMENTS];
float max_salary_expense = 0.0;
char top_department[MAX_NAME_LENGTH];
scanf("%d",&num_departments);
for( i = 0;i < num_departments; i++){
scanf("%s",departments[i].name);
scanf("%d", &departments[i].num_employees);
for( j= 0; j < departments[i].num_employees; j++){
scanf("%s",departments[i].employees[j].name);
scanf("%d", &departments[i].employees[j].emp_id);
scanf("%f", &departments[i].employees[j].salary);
}
}
for( i = 0; i < num_departments; i++){
float total_salary = calculate_total_salary(departments[i]);
printf("%s: %.2f\n", departments[i].name, total_salary);
if (total_salary > max_salary_expense){
max_salary_expense = total_salary;
strcpy(top_department, departments[i].name);
}
}
printf("%s\n",top_department);
return 0;

Page No: 261


}

Execution Results - All test cases have succeeded!

ID: 247Y1A6790
Test Case - 1

User Output
2
Developer
2
Alice 1234 50000.00
Bob 5678 60000.00

2024-2028-CSD-B
Tester
3
Charlie 9876 55000.00
David 5432 75000.00
Eve 8765 40000.00
Developer: 110000.00

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Tester: 170000.00
Tester

Test Case - 2

User Output
3
HR
1
John 1234 45000.00
Sales
2
Mary 5678 55000.00
Sam 9876 48000.00
Marketing
3
Emily 1357 60000.00
Michael 7890 70000.00
HR: 45000.00

Page No: 262


Sales: 103000.00
Marketing: 182000.00
Marketing

ID: 247Y1A6790
Test Case - 3

User Output
2
Developer
1
Amelia 1233 89799.00
Tester
1

2024-2028-CSD-B
Andrin 7887 78000.00
Developer: 89799.00
Tester: 78000.00
Developer

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 4

User Output
1
Engineering
4
Alex 1234 60000.00
Ben 5678 55000.00
Carl 9876 70000.00
Diana 5432 65000.00
Engineering: 250000.00
Engineering
Date: 2025-01-
S.No: 111 Exp. Name: Student Details

Page No: 263


06

Aim:
You have been assigned the task of developing a student grading system for a
prestigious college. Design a program using structures that store student details, such as

ID: 247Y1A6790
name, roll number, and marks in various subjects. Implement an array of structures to
store multiple student records and calculate the overall percentage for each student.
Additionally, provides a functionality to generate a grade for each student based on their
percentage and display it alongside their record.

Input Format:
• The first line contains an integer n, representing No. of students.
• The next line contains input from the user for Name, Roll number and Student
marks (Assume 5 subjects) in one line.

2024-2028-CSD-B
Output Format:
• Return structure with the given members.

Grading Criteria:
A: If the percentage is 90 or above.
B: If the percentage is 80 or above.
C: If the percentage is 70 or above.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


D: If the percentage is 60 or above.
F: If the percentage is below 60.

Source Code:

student.c
//#include <stdio.h>#include <string.h>struct{};int main() {

Page No: 264


//}
#include <stdio.h>
#include <string.h>
struct Student{
char name[100];
int roll_number;

ID: 247Y1A6790
int marks[5];
float percentage;
char grade;
};
void cal_per_and_grade(struct Student* student){
int total_marks=0;
for(int i=0;i<5;i++){
total_marks+=student->marks[i];
}
student->percentage=(float)total_marks/5;

2024-2028-CSD-B
if(student->percentage >=90){
student->grade= 'A';
}else if(student->percentage >=80){
student->grade= 'B';
}
else if(student->percentage >=60){
student->grade ='C';

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
else if(student->percentage >=50){
student->grade ='D';
}
else{
student->grade ='F';
}
}
int main() {
int num_students;
scanf("%d",&num_students);
getchar();
struct Student students[num_students];
for(int i=0;i<num_students;i++){
scanf("%s",students[i].name);
scanf("%d",&students[i].roll_number);
for(int j=0;j<5;j++){
scanf("%d",&students[i].marks[j]);
}
cal_per_and_grade(&students[i]);
}
for(int i=0;i<num_students;i++){
printf("Name: %s\n",students[i].name);

Page No: 265


printf("Roll number: %d\n",students[i].roll_number);
printf("Percentage: %.2f\n",students[i].percentage);
printf("Grade: %c\n",students[i].grade);
}
return 0;
}

ID: 247Y1A6790
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
1

2024-2028-CSD-B
Steven
45
78 89 88 90 75
Name: Steven
Roll number: 45

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Percentage: 84.00
Grade: B

Test Case - 2

User Output
3
John
101
98 90 92 88 91
Alice
102
85 78 90 92 80
Bob
103
75 80 68 88 70
Name: John
Roll number: 101
Percentage: 91.80
Grade: A

Page No: 266


Name: Alice
Roll number: 102
Percentage: 85.00
Grade: B
Name: Bob

ID: 247Y1A6790
Roll number: 103
Percentage: 76.20
Grade: C

Test Case - 3

User Output
2

2024-2028-CSD-B
Emma
201
94 86 89 92 88
Sophia
202
78 82 86 90 76

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Name: Emma
Roll number: 201
Percentage: 89.80
Grade: B
Name: Sophia
Roll number: 202
Percentage: 82.40
Grade: B

Test Case - 4

User Output
1
Liam
301
88 90 94 92 85
Name: Liam
Roll number: 301
Grade: B

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 267
Exp. Name: Average years of service of Date: 2025-01-
S.No: 112

Page No: 268


the soldiers. 06

Aim:
You are developing a soldier management system for an army unit. Each soldier's record
consists of the following information: name, rank, and years of service. Implement an

ID: 247Y1A6790
array of structures to store the records of multiple soldiers. Write a C program to
calculate and display the average years of service for all soldiers in the unit.

Input Format:
• The first line contains an integern, representing No. of soldiers.
• The next line contains input from the user for Name, Rank and years of service of
soldiers.
Output Format:
• Return average years of service of the soldiers.
Source Code:

2024-2028-CSD-B
soldier.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>

Page No: 269


#include<string.h>
struct Soldier{
char name[100];
int rank;
int years_of_service;
};

ID: 247Y1A6790
float cal_avg_yrs(struct Soldier soldiers[],int n){
int total_years=0;
for(int i=0;i<n;i++){
total_years+=soldiers[i].years_of_service;
}
return (float) total_years / n;
}
int main(){
int n;
scanf("%d",&n);

2024-2028-CSD-B
struct Soldier soldiers[n];
for(int i=0;i<n;i++){
scanf("%s",soldiers[i].name);
scanf("%d",&soldiers[i].rank);
scanf("%d",&soldiers[i].years_of_service);
}
float avg_years=cal_avg_yrs(soldiers,n);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


printf("%.2f\n",avg_years);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
Henry
67
42
Jackson
34
43
Test Case - 2

Page No: 270


User Output
3
Henry
67

ID: 247Y1A6790
42
Jackson
34
43
Liam
56
38
41.00

2024-2028-CSD-B
Test Case - 3

User Output
2
Emma

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


45
28
Sophia
38
32
30.00

Test Case - 4

User Output
1
Amelia
50
35
35.00
Exp. Name: Ship Management System Date: 2025-01-
S.No: 113

Page No: 271


for Naval Fleet 06

Aim:
You are working on a ship management system for a naval fleet. Each ship's record
contains the following details: name, type (e.g., aircraft carrier, destroyer), and year of

ID: 247Y1A6790
commissioning. Implement an array of structures to store the ship records. Write a C
program to search for a specific type of ship within the fleet and display the names of all
ships belonging to that type.

Input Format:
• The first line contains an integern, representing No. of ships.
• The next line contains input from the user for the Name, type and year of
commissioning of n ships.
Output Format:
• The program should return the names of ships of the specified type. If no ships of

2024-2028-CSD-B
the specified type are found, it should display "No ships of type '[Type]' found in
the fleet." where '[Type]' is the type you're searching for.
Source Code:

ship.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>

Page No: 272


#include<string.h>
struct Ship{
char name[100];
char type[50];
int year_of_commissioning;
};

ID: 247Y1A6790
void search_ship_by_type(struct Ship ships[],int n,const char*
search_type){
int found=0;
for(int i=0;i<n;i++){
if(strcmp(ships[i].type,search_type)==0){
printf("Name of ship %d is %s\n",i+1,ships[i].name);
found=1;
}
}
if(!found){

2024-2028-CSD-B
printf("No ships of type '%s' found in the fleet\n",search_type);
}
}
int main(){
int n;
char search_type[50];
scanf("%d",&n);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


getchar();
struct Ship ships[n];
for(int i=0;i<n;i++){
scanf("%s",ships[i].name);
scanf("%s",ships[i].type);
scanf("%d",&ships[i].year_of_commissioning);
getchar();
}
scanf("%s",search_type);
search_ship_by_type(ships,n,search_type);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
Windsong Cruise 2013

Page No: 273


Auriula Cargo 2015
Cargo
Name of ship 2 is Auriula

ID: 247Y1A6790
Test Case - 2

User Output
3
Titanic AircraftCarrier 2000
QueenMary Battleship 2005
Olympic AircraftCarrier 2010
AircraftCarrier

2024-2028-CSD-B
Name of ship 1 is Titanic
Name of ship 3 is Olympic

Test Case - 3

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


5
Titanic Cruise 1912
QueenMary Cruise 1936
Nimitz AircraftCarrier 1975
Yamato Battleship 1941
Bismarck Battleship 1940
Cruise
Name of ship 1 is Titanic
Name of ship 2 is QueenMary

Test Case - 4

User Output
2
Titanic Cruise 2000
QueenMary Cruise 2005
AircraftCarrier
Exp. Name: Find Pilot with Highest Date: 2025-01-
S.No: 114

Page No: 274


Flight Hours 06

Aim:
You have been assigned the task of developing a pilot roster system for an Air Force
squadron. Each pilot's record includes the following information: name, rank, and flight

ID: 247Y1A6790
hours. Implement an array of structures to store the pilot records. Write a C program to
find and display the pilot with the highest number of flight hours in the squadron.

Input Format:
• The first line contains an integern, representing No. of pilots.
• The next line contains input from the user for the Name, Rank and flight hours of n
pilots.
Output Format:
• Return the pilot with highest number of flight hours.
Source Code:

2024-2028-CSD-B
pilot.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>

Page No: 275


#include<string.h>
struct Pilot{
char name[100];
char rank[50];
int fh;
};

ID: 247Y1A6790
int main(){
int n;
scanf("%d",&n);
struct Pilot p[n];
for(int i=0;i<n;i++){
scanf("%s",p[i].name);
scanf("%s",p[i].rank);
scanf("%d",&p[i].fh);
}
int maxfh=p[0].fh;

2024-2028-CSD-B
int index=0;
for(int i=1;i<n;i++){
if(p[i].fh>maxfh){
maxfh=p[i].fh;
index=i;
}
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


printf("%s\n",p[index].name);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
3
John 5 120
Alice 7 150
Bob 4 180
Bob

Test Case - 2
User Output

Page No: 276


4
Emma 6 200
William 5 220
Sophia 7 180
James 8 250

ID: 247Y1A6790
James

Test Case - 3

User Output
2
Olivia 4 100
Liam 6 300

2024-2028-CSD-B
Liam

Test Case - 4

User Output
2

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Sophia 8 500
Oliver 6 450
Sophia
Date: 2025-01-
S.No: 117 Exp. Name: Customer Billing System

Page No: 277


06

Aim:
You have been assigned the task of creating a customer billing system using an array of
structures. Each structure should store the customer's name, account number, and total

ID: 247Y1A6790
amount due. Implement functions to add customer records, display all records, and find
the customer with the highest amount due.

Input Format:
• First line of input contains an integer K denoting the no of customers
• Next lines contains details of the K customers: Name (N), Account number (A),
Amount Due (D) in each line

Output Format:
• Firstly, display all the customers name, account number, and amount due.

2024-2028-CSD-B
• Finally, print the customer name with highest due.

Constraints
• N consists of English letters only
• 1 <= N <= 50
• 5 <= length.AccountNumber <= 12
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


CustomerBillingSystem.c
#include<stdio.h>

Page No: 278


#include<string.h>
struct Customer{
char name[51];
char account_number[13];
float amount_due;
};

ID: 247Y1A6790
void addCustomerRecords(struct Customer customers[],int k){
for(int i=0;i<k;i++){
getchar();
fgets(customers[i].name,sizeof(customers[i].name),stdin);
customers[i].name[strcspn(customers[i].name,"\n")]='\0';
fgets(customers[i].account_number,sizeof(customers[i].account_number),stdin);
customers[i].account_number[strcspn(customers[i].account_number,"\n")]='\0';
scanf("%f",&customers[i].amount_due);
}
}

2024-2028-CSD-B
void displayCustomerRecords(struct Customer customers[],int k){
for(int i=0;i<k;i++){
printf("%s ",customers[i].name);
printf("%s ",customers[i].account_number);
printf("%.2f\n",customers[i].amount_due);
}
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


void findHighestDueCustomer(struct Customer customers[],int k){
int highestIndex=0;
for(int i=1;i<k;i++){
if(customers[i].amount_due>customers[highestIndex].amount_due){
highestIndex=i;
}
}
printf("%s ",customers[highestIndex].name);
printf("%.2f\n",customers[highestIndex].amount_due);
}
int main(){
int k;
scanf("%d",&k);
struct Customer customers[k];
addCustomerRecords(customers,k);
displayCustomerRecords(customers,k);
findHighestDueCustomer(customers,k);
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 279


Test Case - 1

User Output
3

ID: 247Y1A6790
A
13245
330
B
98765
213
C
675476
778

2024-2028-CSD-B
A 13245 330.00
B 98765 213.00
C 675476 778.00
C 778.00

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
2
Abc
15948
521
XYZ
357865
423
Abc 15948 521.00
XYZ 357865 423.00
Abc 521.00

Test Case - 3

User Output
1
1548796
745.5

Page No: 280


Roman 1548796 745.50
Roman 745.50

Test Case - 4

ID: 247Y1A6790
User Output
2
Alpha
124563
986.5
Beta
357842

2024-2028-CSD-B
954.6
Alpha 124563 986.50
Beta 357842 954.60
Alpha 986.50

Test Case - 5

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
1
Gamma
6482553
1005
Gamma 6482553 1005.00
Gamma 1005.00
Exp. Name: Car Inventory Management Date: 2025-01-
S.No: 118

Page No: 281


System 06

Aim:
You are working on a car inventory management system using an array of structures. Each
structure should hold the details of a car, including the make, model, and year of

ID: 247Y1A6790
manufacture. Implement functions to add car records, display all records, and find the
newest car in the inventory.

Input Format:
First line of input contains an integer X denoting the no of cars in inventory.
Next lines contains details of X cars: car maker name (N) of character datatype, model
name (M) of character datatype, year (yyyy) of integer type in each line.

Output Format:
Firstly, display all the records and then the details of the newest car.

2024-2028-CSD-B
Constraints:
1 <= N <= 50
1 <= M <= 50
Source Code:

CarInventory.c

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


#include<stdio.h>

Page No: 282


#include<string.h>
struct Car{
char make[51];
char model[51];
int year;
};

ID: 247Y1A6790
void add(struct Car cars[],int x){
for(int i=0;i<x;i++){
getchar();
fgets(cars[i].make,sizeof(cars[i].make),stdin);
cars[i].make[strcspn(cars[i].make,"\n")]='\0';
fgets(cars[i].model,sizeof(cars[i].model),stdin);
cars[i].model[strcspn(cars[i].model,"\n")]='\0';
scanf("%d",&cars[i].year);
}
}

2024-2028-CSD-B
void display(struct Car cars[],int x){
for(int i=0;i<x;i++){
printf("%s\n",cars[i].make);
printf("%s\n",cars[i].model);
printf("%d\n",cars[i].year);
}
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


void find(struct Car cars[],int x){
int newestIndex=0;
for(int i=1;i<x;i++){
if(cars[i].year>cars[newestIndex].year){
newestIndex=i;
}
}
printf("%s ",cars[newestIndex].make);
printf("%s ",cars[newestIndex].model);
printf("%d\n",cars[newestIndex].year);
}
int main(){
int x;
scanf("%d",&x);
struct Car cars[x];
add(cars,x);
display(cars,x);
find(cars,x);
return 0;
}
Execution Results - All test cases have succeeded!

Page No: 283


Test Case - 1

User Output
3

ID: 247Y1A6790
Mervedes-Benz
A-Class
2022
Nissan
Altima
2023
Ford
Escape
2020

2024-2028-CSD-B
Mervedes-Benz
A-Class
2022
Nissan
Altima
2023

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Ford
Escape
2020
Nissan Altima 2023

Test Case - 2

User Output
2
Ford
Altima
2021
Nissan
Escape
2022
Ford
Altima
2021
Escape
2022

Page No: 284


Nissan Escape 2022

Test Case - 3

ID: 247Y1A6790
User Output
3
Australia
FordFalcon
1960
Argentina
ToyotaHiLux
1960
Brazil

2024-2028-CSD-B
Volkswagen
1980
Australia
FordFalcon
1960
Argentina

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


ToyotaHiLux
1960
Brazil
Volkswagen
1980
Brazil Volkswagen 1980

Test Case - 4

User Output
2
China
WulingHongguang
2010
France
RenaultClio
1990
WulingHongguang
2010

Page No: 285


France
RenaultClio
1990
China WulingHongguang 2010

ID: 247Y1A6790
Test Case - 5

User Output
1
CzechRepublic
SkodaOctivia
1996
CzechRepublic

2024-2028-CSD-B
SkodaOctivia
1996
CzechRepublic SkodaOctivia 1996

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Exp. Name: Product Inventory Date: 2025-01-
S.No: 119

Page No: 286


Management System 06

Aim:
You are developing a product inventory management system for a retail store. Each
product has a unique identifier, name, price, and quantity in stock. Implement an array of

ID: 247Y1A6790
structures to store the product records. Create functions to add new products, update
product details, display all products, and search for products based on their identifier or
name.

Input Format:
Enter your choice 'C' as an integer value
Enter product identifier 'I' in string
Enter product name 'N' as string
Enter product price 'P' as integer
Enter product quantity 'Q' as integer

2024-2028-CSD-B
Note:
If C == 1, it means to insert a product
If C == 2, it means to print the count of no of products and the details of the products
If C == 3, it means to search for a product
If C == 4, it means to means to exit from the program

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Output Format:
Choice as integer value Product identifier as string Product name as string Product price
as integer Product quantity as integer

Constraints:
1 <= C <= 4
1 <= I.length <= 50
1 <= N.length <= 50
1 <= P <= 100
1 <= Q <= 100
Source Code:

ProductInventory.c
#include<stdio.h>

Page No: 287


#include<string.h>
#define max 100
struct Pro{
char iden[51];
char name[51];
int price;

ID: 247Y1A6790
int quantity;
};
void add(struct Pro pros[],int *count){
if(*count >=max){
return;
}
getchar();
fgets(pros[*count].iden,sizeof(pros[*count].iden),stdin);
pros[*count].iden[strcspn(pros[*count].iden,"\n")]='\0';
fgets(pros[*count].name,sizeof(pros[*count].name),stdin);

2024-2028-CSD-B
pros[*count].name[strcspn(pros[*count].name,"\n")]='\0';
scanf("%d",&pros[*count].price);
scanf("%d",&pros[*count].quantity);
(*count)++;
}
void display(struct Pro pros[],int count){
if(count==0){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return;
}
printf("%d\n",count);
for(int i=0;i<count;i++){
printf("%s ",pros[i].iden);
printf("%s ",pros[i].name);
printf("%d ",pros[i].price);
printf("%d\n",pros[i].quantity);
}
}
void search(struct Pro pros[],int count){
char searcht[51];
getchar();
fgets(searcht,sizeof(searcht),stdin);
searcht[strcspn(searcht,"\n")]='\0';
int found=0;
for(int i=0;i<count;i++){
if(strcmp(pros[i].iden,searcht)==0||strcmp(pros[i].name,searcht)==0){
printf("Product Found: ");
printf("%s ",pros[i].iden);
printf("%s ",pros[i].name);
printf("%d ",pros[i].price);
printf("%d\n",pros[i].quantity);

Page No: 288


found=1;
break;
}
}
if(!found){
printf("Product Not Found\n");

ID: 247Y1A6790
}
}
int main(){
struct Pro pros[max];
int proc=0;
int choice;
while(1){
scanf("%d",&choice);
if(choice==1){
add(pros,&proc);

2024-2028-CSD-B
}
else if(choice==2){
display(pros,proc);
if(proc==0)
printf("%d\n",proc);
}
else if(choice==3){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


search(pros,proc);
}
else if(choice==4){
break;
}
else{
printf("invalid choice. please try again.\n");
}
}
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
3
apple
Product Not Found

Page No: 289


4

Test Case - 2

ID: 247Y1A6790
User Output
1
PAPL
PineApple
15
20
2
1

2024-2028-CSD-B
PAPL PineApple 15 20
4

Test Case - 3

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3
Apple
Product Not Found
2
0
1
WTML
WaterMelon
5
35
2
1
WTML WaterMelon 5 35
4

Test Case - 4

User Output
2
0

Page No: 290


1
Bnn
Banana
48

ID: 247Y1A6790
10
2
1
Bnn Banana 48 10
1
APL
apple
50
25

2024-2028-CSD-B
1
DGN
DragonFruit
10
120

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


2
3
Bnn Banana 48 10
APL apple 50 25
DGN DragonFruit 10 120
3
APL
Product Found: APL apple 50 25
3
apple
Product Found: APL apple 50 25
3
WaterMelon
Product Not Found
4

Test Case - 5
1
Ferrero

Page No: 291


milk
100
2
1

ID: 247Y1A6790
truffle
haz
12
1
1
disko
choco
290

2024-2028-CSD-B
12
2
3
Ferrero milk 100 2
truffle haz 12 1
disko choco 290 12

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


3
truffle
Product Found: truffle haz 12 1
4
Date: 2025-01-
S.No: 120 Exp. Name: Managing bank accounts

Page No: 292


06

Aim:
You are tasked with managing bank accounts for two clients: one with the State Bank of
India (SBI) and another with the ICICI Bank. You need to implement a system where the

ID: 247Y1A6790
bank account details can be inquired, and money can be withdrawn based on user input.
Create a class Account with attributes: name, id, and balance. Implement methods
to: Inquire about the balance. Withdraw money if sufficient balance is available.

Input Format:
• Enter the name, ID, and initial balance for the SBI account.
• Enter the name, ID, and initial balance for the ICICI account.
• For each account, specify the amount to withdraw.

Output Format:

2024-2028-CSD-B
• Display the details of each account.
• Show the results of the withdrawal operations including success or failure
messages.

Note: Refer to the visible test cases for the input and output layout of the program
Source Code:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


bankOperations.c
#include<iostream>

Page No: 293


#include <string>
using namespace std;
class Account
{
public:
string name;

ID: 247Y1A6790
string id;
float balance;
Account (string acc_name,string acc_id,float acc_balance)
{
name=acc_name;
id=acc_id;
balance=acc_balance;
}
void inquire_balance()
{

2024-2028-CSD-B
cout<<name<<endl;
cout<<id<<endl;
cout<<balance<<endl;
}
void withdraw(float amount)
{
if (amount<=balance){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


balance-=amount;
cout<<"Amount withdrawn: "<<amount <<endl;
cout <<"New Balance: "<<balance<<endl;
}else{
cout <<"Insufficient balance to withdraw "<< amount
<<endl;
}
}
};
int main()
{
string name,id;
float balance, withdraw_amount;
getline(cin,name);
getline(cin,id);
cin>>balance;
Account sbi_account(name,id,balance);
cin.ignore();
getline(cin,name);
getline(cin,id);
cin>>balance;
Account icic_account(name,id,balance);
cout<<"SBI Account Details:"<<endl;

Page No: 294


sbi_account.inquire_balance();
cin>>withdraw_amount;
sbi_account.withdraw(withdraw_amount);
cout<<"ICICI Account Details:"<<endl;
icic_account.inquire_balance();
cin>>withdraw_amount;

ID: 247Y1A6790
icic_account.withdraw(withdraw_amount);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

2024-2028-CSD-B
User Output
ram
123
6790
yash

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


789
9000
SBI Account Details:
ram
123
6790
78
Amount withdrawn: 78
New Balance: 6712
ICICI Account Details:
yash
789
9000
10000
Insufficient balance to withdraw 10000

Test Case - 2
alia
678

Page No: 295


90000
harish
6765
90500

ID: 247Y1A6790
SBI Account Details:
alia
678
90000
500
Amount withdrawn: 500
New Balance: 89500
ICICI Account Details:
harish

2024-2028-CSD-B
6765
90500
1000
Amount withdrawn: 1000
New Balance: 89500

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Exp. Name: Banking Application with Date: 2025-01-
S.No: 122

Page No: 296


Different Account Types 06

Aim:
You are tasked with implementing a banking application that handles three types of
accounts: SavingsAccount, CheckingAccount, and LoanAccount. Each account

ID: 247Y1A6790
type has specific behaviors for depositing, withdrawing, and maintaining a balance.
• SavingsAccount: Starts with an initial balance of $1000.
• CheckingAccount: Starts with an initial balance of $2000.
• LoanAccount: Starts with an amount owed of $50,000. Deposits reduce the owed
amount, while withdrawals increase it.

The application uses an abstract base class called Account. This class defines common
methods such as deposit(), withdraw(), and getBalance(), which must be
implemented by all derived classes. This allows users to interact with different account

2024-2028-CSD-B
types through a common interface without needing to understand the specific details of
each account type.

Requirements:
Abstract Base Class: Account
Methods:
• deposit(double amount)

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• withdraw(double amount)
• getBalance()

Derived Classes(Subclasses)

A. Class SavingsAccount
• Attributes: balance
• A constructor which initializes the balance to 1000
• Override deposit(double amount) to add the amount to the balance
• Override withdraw(double amount) to reduce the given amount from
balance if the amount is less than the balance.
• Override getBalance() to return the balance amount

B. Class CheckingAccount
• Attributes: balance
• A constructor which initializes the balance to 2000
• Override deposit(double amount) to add the amount to the balance
• Override withdraw(double amount) to reduce the given amount from balance
if the amount is less than the balance.
• Override getBalance() to return the balance amount
C. Class LoanAccount
• Attributes: balance

Page No: 297


• A constructor which initializes the balance to 50000
• Override deposit(double amount) to reduce the amount from the balance
which simulates paying off the loan process
• Override withdraw(double amount) to add the given amount to balance
• Override getBalance() to return the balance amount

ID: 247Y1A6790
The program should allow users to perform the following operations:
14. Choose an account type.
15. Deposit a specified amount.
16. Withdraw a specified amount.
17. Display the current balance.

Input Format:
The user first selects the type of account:

2024-2028-CSD-B
• 1 for SavingsAccount
• 2 for CheckingAccount
• 3 for LoanAccount
After selecting an account type, the user enters an amount to deposit.
The user then enters an amount to withdraw.

Output Format:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The program should display the current balance after transaction (deposit and
withdrawal).
• If a withdrawal exceeds the available balance, the program should output
"Insufficient funds".
Source Code:

bankApplication.cpp
#include <iostream>

Page No: 298


#include <string>
using namespace std;
class Account {
public:
virtual void deposit(double amount)=0;
virtual void withdraw(double amount)=0;

ID: 247Y1A6790
virtual double getBalance() const=0;
virtual ~Account() {}
};
class SavingsAccount : public Account {
public:
double balance;
public:
SavingsAccount() : balance(1000) {}
void deposit(double amount) override {
balance+=amount;

2024-2028-CSD-B
}
void withdraw(double amount)override{
if(amount <= balance){
balance-=amount;
}
else{
cout << "Insufficient funds"<< endl;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
}
double getBalance() const override{
return balance;
}
};
// Concrete class: CheckingAccount
class CheckingAccount : public Account {
public:
double balance;
public:
CheckingAccount() : balance(2000) {}
void deposit(double amount) override{
balance+=amount;
}
void withdraw(double amount) override{
if(amount <= balance){
balance-=amount;
}
else{
cout <<"Insufficient funds" << endl;
}
}

Page No: 299


double getBalance() const override{
return balance;
}
};
// Concrete class: LoanAccount
class LoanAccount : public Account {

ID: 247Y1A6790
public:
double balance;
public:
LoanAccount(): balance(50000) {}
void deposit(double amount) override{
balance-=amount;
}
void withdraw(double amount) override{
balance+=amount;
}

2024-2028-CSD-B
double getBalance() const override{
return balance;
}
};

int main() {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Account* accounts[3];
accounts[0] = new SavingsAccount();
accounts[1] = new CheckingAccount();
accounts[2] = new LoanAccount();

int choice;
double amount;

std::cout << "Choose an account type to operate on:\n";


std::cout << "1. Savings Account\n";
std::cout << "2. Checking Account\n";
std::cout << "3. Loan Account\n";
std::cin >> choice;

switch (choice) {
case 1:
std::cin >> amount;
accounts[0]->deposit(amount);
std::cin >> amount;
accounts[0]->withdraw(amount);
std::cout << accounts[0]->getBalance() << "\n";
break;
case 2:

Page No: 300


std::cin >> amount;
accounts[1]->deposit(amount);
std::cin >> amount;
accounts[1]->withdraw(amount);
std::cout << accounts[1]->getBalance() << "\n";
break;

ID: 247Y1A6790
case 3:
std::cin >> amount;
accounts[2]->deposit(amount);
std::cin >> amount;
accounts[2]->withdraw(amount);
std::cout << accounts[2]->getBalance() << "\n";
break;
default:
std::cout << "Invalid choice\n";
break;

2024-2028-CSD-B
}

// Clean up
for (int i = 0; i < 3; ++i) {
delete accounts[i];
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose an account type to operate on:
1. Savings Account
2. Checking Account
3. Loan Account
1
2000
4000
Insufficient funds
3000
Test Case - 2

Page No: 301


User Output
Choose an account type to operate on:
1. Savings Account
2. Checking Account

ID: 247Y1A6790
3. Loan Account
2
1000
500
2500

Test Case - 3

User Output

2024-2028-CSD-B
Choose an account type to operate on:
1. Savings Account
2. Checking Account
3. Loan Account
3
4000

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


500
46500
Exp. Name: GUI Library for Button Date: 2025-01-
S.No: 123

Page No: 302


Types Using Inheritance 06

Aim:
You are developing a graphical user interface (GUI) library that includes various types of
buttons. The base class is Button, and you will create subclasses such as ImageButton,

ID: 247Y1A6790
ToggleButton, and RadioButton.

Requirements:
Base Class: Button
Properties:
• label: A string representing the button's label.
• size: An integer representing the button's size.
Methods:
• click(): A method that simulates clicking the button.

2024-2028-CSD-B
Derived Subclasses:

A. Class ImageButton:
• An attribute imagePath (std::string): This private member variable holds
the file path of the image associated with the button
• A Constructor ImageButton(const std::string& lbl, int sz, const

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


std::string& imgPath): where lbl: A string for the button's label (inherited
from the base class), sz: An integer representing the size of the button (also
inherited), imgPath: A string that specifies the path to the image.
• click():This method overrides a virtual function from the base class Button. It
provides a specific implementation for the ImageButton class, which outputs a
message indicating that the button has been clicked.

B. Class ToggleButton:
• An attribute isOn (bool): This private member variable holds the current state
of the toggle button. It indicates whether the button is in the "ON" state (true) or
"OFF" state (false).
• A Constructor ToggleButton(const std::string& lbl, int sz, int
state): which takes three parameters: lbl: A string for the button's label
(inherited from the base class), sz: An integer representing the size of the button
(also inherited), state: An integer that specifies the initial state of the toggle
button, which is used to set the isOn attribute.
• click(): This method overrides a virtual function from the base class Button. It
provides a specific implementation for the ToggleButton class, which outputs a
message indicating the current state of the button after it has been toggled.
• An attribute group (std::string): This private member variable holds the
name of the group to which the radio button belongs.

Page No: 303


• A Constructor RadioButton(const std::string& lbl, int sz, const
std::string& grp): which takes three parameters: lbl: A string for the
button's label (inherited from the base class), sz: An integer representing the size
of the button (also inherited), grp: A string that specifies the group name to
which the radio button belongs.

ID: 247Y1A6790
• click(): This method overrides a virtual function from the base class Button.
It provides a specific implementation for the RadioButton class, which outputs a
message indicating that the button has been selected.

Input Format:
The program will prompt the user to select a button type and then provide the necessary
details based on the selected button type.
Choose Button Type:
• 1 for Image Button
• 2 for Toggle Button

2024-2028-CSD-B
• 3 for Radio Button
Input Details:
For Image Button:
• Label (string): The label of the button.
• Size (integer): The size of the button.
• Image Path (string): The path to the image.
For Toggle Button:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• Label (string): The label of the button.
• Size (integer): The size of the button.
• State (integer): The initial state (0 for OFF, 1 for ON).
For Radio Button:
• Label (string): The label of the button.
• Size (integer): The size of the button.
• Group (string): The group name for the radio button.

Output Format:
The output will depend on the type of button selected:
• ImageButton: Message format: ImageButton [label] clicked with image:
[imagePath]
• ToggleButton: Message format: ToggleButton [label] toggled [ON/OFF]
• RadioButton: Message format: RadioButton [label] selected in group: [group]
Source Code:

guiLibrary.cpp
#include <iostream>

Page No: 304


#include <string>
using namespace std;
// Base class
class Button {
public:
string label;

ID: 247Y1A6790
int size;
public:
Button(const string& lbl,int sz) : label(lbl),size(sz) {}
virtual void click()=0;
virtual ~Button() {}
};
// Subclass: ImageButton
class ImageButton : public Button {
private:
string imagePath;

2024-2028-CSD-B
public:
ImageButton(const string& lbl,int sz,const string& imgPath)
: Button(lbl,sz),imagePath(imgPath) {}
void click() override{
cout << "ImageButton " <<label << " clicked with image: "
<<imagePath << endl;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


};
// Subclass: ToggleButton
class ToggleButton : public Button {
private:
bool isOn;
public:
ToggleButton(const string& lbl,int sz,int state)
: Button(lbl,sz),isOn(state==1) {}
void click() override{
isOn=!isOn;
cout << "ToggleButton " << label << " toggled " << (isOn ?
"OFF" : "ON") << endl;
}
};
// Subclass: RadioButton
class RadioButton : public Button {
private:
string group;
public:
RadioButton(const string& lbl,int sz,const string& grp)
: Button(lbl,sz),group(grp) {}
void click() override{
cout << "RadioButton " << label << " selected in group: " <<

Page No: 305


group << endl;
}
};

ID: 247Y1A6790
int main() {
int buttonType;
std::cout << "Choose button type:\n";
std::cout << "1. Image Button\n";
std::cout << "2. Toggle Button\n";
std::cout << "3. Radio Button\n";
std::cin >> buttonType;

std::string label;
int size,state;

2024-2028-CSD-B
Button* button = nullptr;

switch (buttonType) {
case 1: { // Image Button
std::string imagePath;
std::cin >> label;
std::cin >> size;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


std::cin >> imagePath;
button = new ImageButton(label, size, imagePath);
break;
}
case 2: { // Toggle Button
std::cin >> label;
std::cin >> size;
std::cin >> state;
button = new ToggleButton(label, size, state);
break;
}
case 3: { // Radio Button
std::string group;
std::cin >> label;
std::cin >> size;
std::cin >> group;
button = new RadioButton(label, size, group);
break;
}
default:
std::cout << "Invalid choice\n";
return 1;
}

Page No: 306


// Simulate button click
button->click();

// Clean up
delete button;

ID: 247Y1A6790
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

2024-2028-CSD-B
User Output
Choose button type:
1. Image Button
2. Toggle Button
3. Radio Button
1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Pic1
200
src.png
ImageButton Pic1 clicked with image: src.png

Test Case - 2

User Output
Choose button type:
1. Image Button
2. Toggle Button
3. Radio Button
2
Tog1
200
1
ToggleButton Tog1 toggled ON
Test Case - 3

Page No: 307


User Output
Choose button type:
1. Image Button
2. Toggle Button

ID: 247Y1A6790
3. Radio Button
3
radio1
200
language
RadioButton radio1 selected in group: language

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Exp. Name: E-Commerce Platform with Date: 2025-01-
S.No: 124

Page No: 308


Product Inheritance 06

Aim:
You are tasked with creating a simple e-commerce system using object-oriented
programming in C++. You will implement a base class Product and three derived

ID: 247Y1A6790
classes: Electronics, Clothing, and Books according to the following
requirements.

Requirements:
Base Class: Product

Attributes:
• name (string): The name of the product.
• price (double): The price of the product.

Methods:

2024-2028-CSD-B
• A constructor to initialize name and price.
• applyDiscount(double percentage): Reduces the product price by the
given percentage.
• display(): Displays the product's name and price.

Derived Classes (Subclasses):

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


A. Class Electronics:
• Additional attribute: warrantyPeriod (int): The warranty period in months.
• Override display() to show the product's name, price, and warranty period.

B. Class Clothing:
• Additional attributes:
• size (string): The size of the clothing (e.g., "M", "L", "XL").
• color (string): The color of the clothing (e.g., "Red", "Blue").
• Override display() to show the product's name, price, size, and color.

C. Class Books:
• Additional attribute: author (string): The author of the book.
• Override display() to show the product's name, price, and author.

Input Format:
1.The program will first prompt the user to choose the product type:
• 1 for Electronics

Page No: 309


• 2 for Clothing
• 3 for Books
• Any other input will result in the message: "Invalid choice"
2.Then, enter Product Details based on the selected type:
• Electronics: Name (string), Price (double), Warranty Period (int)

ID: 247Y1A6790
• Clothing: Name (string), Price (double), Size (string), Color (string)
• Books: Name (string), Price (double), Author (string)
3.The user will then input the discount percentage (double), which will be applied to the
product price.

Output Format:
The output messages will be displayed in the following format based on the selected
product type:
Electronics:
Product Name: [Product Name]
Price: $[Original Price]

2024-2028-CSD-B
Warranty Period: [Warranty Period] months
Final Price after Discount: $[Final Price]
Clothing:
Product Name: [Product Name]
Price: $[Original Price]
Size: [Size]
Color: [Color]
Final Price after Discount: $[Final Price]

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Books:
Product Name: [Product Name]
Price: $[Original Price]
Author: [Author Name]
Final Price after Discount: $[Final Price]
Source Code:

eCommerce.cpp
#include <iostream>

Page No: 310


#include <string>
using namespace std;
// Base class
class Product {
protected:
string name;

ID: 247Y1A6790
double price;
public:
Product(const string& n,double p) : name(n), price(p) {}
void applyDiscount(double percentage) {
price-=price * (percentage /100);
}
virtual void display() const=0;
virtual ~Product() {}
};
// Subclass: Electronics

2024-2028-CSD-B
class Electronics : public Product{
private:
int warrantyPeriod;
public:
Electronics(const string& n,double p,int w) :
Product(n,p),warrantyPeriod(w) {}
void display() const override{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


cout << "Product Name: " << name <<endl;
cout << "Price: " << price << endl;
cout << "Warranty Period: " << warrantyPeriod << " months" <<
endl;
}
};
// Subclass: Clothing
class Clothing : public Product{
private:
string size;
string color;
public:
Clothing(const string& n,double p,const string& s ,const string& c)
: Product(n,p),size(s),color(c) {}
void display() const override {
cout << "Product Name: " << name << endl;
cout << "Price: " << price << endl;
cout << "Size: " << size <<endl;
cout << "Color: " << color <<endl;
}
};
// Subclass: Books
class Books : public Product{

Page No: 311


private:
string author;
public:
Books(const string& n,double p,const string& a) : Product(n,p),
author(a) {}
void display() const override {

ID: 247Y1A6790
cout << "Product Name: " << name <<endl;
cout << "Price: " <<price <<endl;
cout << "Author: " << author << endl;
}
};

int main() {
int productType;

2024-2028-CSD-B
std::cout << "Choose product type:\n";
std::cout << "1. Electronics\n";
std::cout << "2. Clothing\n";
std::cout << "3. Books\n";
std::cin >> productType;

std::string name;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


double price;
Product* product = nullptr;

switch (productType) {
case 1: { // Electronics
int warranty;
//std::cout << "Enter product name: ";
std::cin >> name;
//std::cout << "Enter price: ";
std::cin >> price;
//std::cout << "Enter warranty period (months): ";
std::cin >> warranty;
product = new Electronics(name, price, warranty);
break;
}
case 2: { // Clothing
std::string size, color;
//std::cout << "Enter product name: ";
std::cin >> name;
//std::cout << "Enter price: ";
std::cin >> price;
//std::cout << "Enter size: ";
std::cin >> size;

Page No: 312


//std::cout << "Enter color: ";
std::cin >> color;
product = new Clothing(name, price, size, color);
break;
}
case 3: { // Books

ID: 247Y1A6790
std::string author;
//std::cout << "Enter product name: ";
std::cin >> name;
//std::cout << "Enter price: ";
std::cin >> price;
//std::cout << "Enter author: ";
std::cin >> author;
product = new Books(name, price, author);
break;
}

2024-2028-CSD-B
default:
std::cout << "Invalid choice\n";
return 1;
}

// Apply a discount and display the product details


double discount;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


//std::cout << "Enter discount percentage: ";
std::cin >> discount;
product->applyDiscount(discount);
product->display();

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose product type:
1. Electronics
2. Clothing
3. Books
1
2000
5

Page No: 313


10
Product Name: Headset
Price: 1800
Warranty Period: 5 months

ID: 247Y1A6790
Test Case - 2

User Output
Choose product type:
1. Electronics
2. Clothing
3. Books
2

2024-2028-CSD-B
Shirt
2100
M
Blue
25
Product Name: Shirt

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Price: 1575
Size: M
Color: Blue

Test Case - 3

User Output
Choose product type:
1. Electronics
2. Clothing
3. Books
3
Book1
500
Ravi
10
Product Name: Book1
Price: 450
Exp. Name: Building Educational Date: 2025-01-
S.No: 125

Page No: 314


Software with Inheritance 06

Aim:
Your task is to create educational software that manages various types of learning
resources. You need to establish a base class called LearningResource that includes

ID: 247Y1A6790
common properties like title and subject, along with a method named display()
for showing resource details.

From this base class, you will derive three subclasses:


A. Class Book:
• An attribute author (std::string)
• A Constructor Book(const std::string& t, const std::string& s,
const std::string& a): It takes three parameters: t: A string for the title of
the book (inherited from the base class LearningResource), s: A string for the

2024-2028-CSD-B
subject of the book (also inherited), a: A string that specifies the author of the
book.
• display() : This method overrides a virtual function from the base class
LearningResource.

B. Class VideoLecture:
• Attributes duration (int), videoURL (std::string)

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• A Constructor VideoLecture(const std::string& t, const
std::string& s, int d, const std::string& url): where t: A string
for the title of the video lecture (inherited from the base class
LearningResource), s: A string for the subject of the video lecture (also
inherited), d: An integer representing the duration of the video in minutes, url: A
string that specifies the URL where the video can be accessed.
• display() : This method overrides a virtual function from the base class
LearningResource.

C. Class Quiz:
• An attribute questions (std::vector<std::string>)
• A Constructor Quiz(const std::string& t, const std::string& s,
const std::vectorstd::string& qs): where t: A string for the title of the
quiz (inherited from the base class LearningResource), s: A string for the
subject of the quiz (also inherited), qs: A vector of strings that contains the
questions for the quiz.
• display() : This method overrides a virtual function from the base class
LearningResource.

Input Format
When the program runs, the user will be prompted to choose a type of learning resource
to create. Depending on the choice, the following inputs will be required:

Page No: 315


For Book:
• Title: [Enter the title of the book]
• Subject: [Enter the subject of the book]
• Author: [Enter the author’s name]
For VideoLecture:

ID: 247Y1A6790
• Title: [Enter the title of the video lecture]
• Subject: [Enter the subject]
• Duration: [Enter the duration in minutes]
• Video URL: [Enter the URL for the video]
For Quiz:
• Title: [Enter the title of the quiz]
• Subject: [Enter the subject]
• Number of Questions: [Enter the number of questions]
• Questions: [Enter each question]

Output Format

2024-2028-CSD-B
Based on the type of learning resource created, the output will be displayed in the
following format:
For Book:
Title: [Title]
Subject: [Subject]
Author: [Author]
For VideoLecture:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Title: [Title]
Subject: [Subject]
Duration: [Duration] minutes
Video URL: [Video URL]
For Quiz:
Title: [Title]
Subject: [Subject]
Questions:
1. [Question 1]
2. [Question 2]
...
Source Code:

educationalApp.cpp
#include <iostream>

Page No: 316


#include <vector>
#include <string>
using namespace std;
class LearningResource {
protected:
string title;

ID: 247Y1A6790
string subject;
public:
LearningResource(const string& t,const string& s) : title(t),
subject(s) {}
virtual void display() const=0;
virtual ~LearningResource() {}
};
class Book : public LearningResource{
private:
string author;

2024-2028-CSD-B
public:
Book(const string& t,const string& s,const string& a)
: LearningResource(t,s),author(a) {}
void display() const override{
cout << "Title: " << title << endl;
cout << "Subject: " << subject << endl;
cout << "Author: " <<author << endl;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
};
class VideoLecture : public LearningResource{
private:
int duration;
string videoURL;
public:
VideoLecture(const string& t,const string& s,int d,const string& url) :
LearningResource(t,s),duration(d),videoURL(url) {}
void display() const override{
cout << "Title: " <<title << endl;
cout << "Subject: " <<subject <<endl;
cout << "Duration: " <<duration <<" minutes" <<endl;
cout << "Video URL: " << videoURL <<endl;
}
};
class Quiz : public LearningResource{
private:
vector<string>questions;
public:
Quiz(const string& t,const string& s,const vector<string>& qs)
: LearningResource(t,s),questions(qs){}
void display() const override{

Page No: 317


cout << "Title: " << title << endl;
cout << "Subject: " << subject << endl;
cout << "Questions:" << endl;
for(size_t i=0;i<questions.size();++i){
cout << questions[i] << endl;
}

ID: 247Y1A6790
}
};

int main() {
int resourceType;
std::cout << "Choose resource type:\n";
std::cout << "1. Book\n";
std::cout << "2. Video Lecture\n";
std::cout << "3. Quiz\n";

2024-2028-CSD-B
std::cin >> resourceType;

std::string title, subject, author, videoURL;


int duration, numQuestions;
std::vector<std::string> questions;

switch (resourceType) {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


case 1: { // Book
std::cin.ignore();
std::getline(std::cin, title);
std::getline(std::cin, subject);
std::getline(std::cin, author);
if (title.empty()) {
std::cout << "Title cannot be empty\n";
return 1;
}
Book book(title, subject, author);
book.display();
break;
}
case 2: { // Video Lecture

std::cin.ignore();
std::getline(std::cin, title);
std::getline(std::cin, subject);
std::cin >> duration;
std::cin.ignore();
std::getline(std::cin, videoURL);
if (duration <= 0) {
std::cout << "Duration must be greater than zero\n";

Page No: 318


return 1;
}
VideoLecture videoLecture(title, subject, duration,
videoURL);
videoLecture.display();
break;

ID: 247Y1A6790
}
case 3: { // Quiz

std::cin.ignore();
std::getline(std::cin, title);
std::getline(std::cin, subject);
std::cin >> numQuestions;
if (numQuestions <= 0) {
std::cout << "Quiz must have at least one question\n";
return 1;

2024-2028-CSD-B
}
std::cin.ignore();
for (int i = 0; i < numQuestions; ++i) {
std::string question;
std::cout << "Enter question " << (i + 1) << ":\n";
std::getline(std::cin, question);
questions.push_back(question);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}
Quiz quiz(title, subject, questions);
quiz.display();
break;
}
default:
std::cout << "Invalid\n";
return 1;
}

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose resource type:
1. Book
2. Video Lecture

Page No: 319


3. Quiz
1
C++ Programming
Computer Science

ID: 247Y1A6790
Bjarne Stroutrup
Title: C++ Programming
Subject: Computer Science
Author: Bjarne Stroutrup

Test Case - 2

User Output
Choose resource type:

2024-2028-CSD-B
1. Book
2. Video Lecture
3. Quiz
2
Advanced Machine Learning
Artificial Intelligence

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


120
example.com/ml-lecture1
Title: Advanced Machine Learning
Subject: Artificial Intelligence
Duration: 120 minutes
Video URL: example.com/ml-lecture1

Test Case - 3

User Output
Choose resource type:
1. Book
2. Video Lecture
3. Quiz
3
Programming Quiz
Computer Science
2
What is a pointer
Enter question 2:

Page No: 320


What is polymorphism
Title: Programming Quiz
Subject: Computer Science
Questions:

ID: 247Y1A6790
What is a pointer
What is polymorphism

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Exp. Name: Design a System to Classify
Date: 2025-01-

Page No: 321


S.No: 126 and Manage Information about
06
Different Animals

Aim:

ID: 247Y1A6790
Problem Statement:
You need to design a system to classify and manage information about various types of
animals. The system should be able to handle common characteristics of animals (such as
name and habitat) as well as specific characteristics based on the type of animal (such as
mammals, birds, and reptiles). The system should support the following actions:

Requirements:

Base Class Animal:


Attributes:
• name: The name of the animal.

2024-2028-CSD-B
• habitat: Where the animal lives (e.g., forest, desert, ocean).
Methods:
• A constructor Animal(const std::string& n, const std::string& h):
This constructor initializes an Animal object. It takes two parameters: n: A string
for the name of the animal, h: A string for the habitat of the animal.
• eat(): Prints the message "The animal is eating"

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• sleep(): Prints the message "The animal is sleeping"
• displayInfo(): This virtual method displays information about the animal. It
outputs: The name and habitat of the animal.

Derived Classes:

A. Class Mammal (inherits from Animal):


Attribute:
• hasFur: Boolean value (true if the mammal has fur, false otherwise).
Methods:
• A constructor Mammal(const std::string& n, const std::string& h,
bool fur): This constructor initializes a Mammal object with three parameters: n:
The name of the mammal, h: The habitat of the mammal, fur: A boolean
indicating if the mammal has fur. It initializes the base class Animal with the name
and habitat, and sets the hasFur member using the provided value.
• nurse(): Prints the message "The mammal is nursing its young"
• displayInfo() : This overridden method provides specific information about
the Mammal class. It does the following: Calls the base class method
Animal::displayInfo() to display the name and habitat. Outputs whether
the mammal has fur, displaying "Yes" or "No" based on the hasFur attribute.
B. Class Bird (inherits from Animal):
Methods:

Page No: 322


• A constructor Bird(const std::string& n, const std::string& h):
This constructor initializes a Bird object with two parameters: n: The name of the
bird, h: The habitat of the bird. It initializes the base class Animal with the
provided name and habitat.
• fly(): Prints the message "The bird is flying"

ID: 247Y1A6790
• displayInfo() : This overridden method does the following: Calls the base class
method Animal::displayInfo() to display the name and habitat of the bird.

C. Class Reptile (inherits from Animal):


Methods:
• A constructor Reptile(const std::string& n, const std::string&
h): This constructor initializes a Reptile object with two parameters: n: The
name of the reptile, h: The habitat of the reptile. It initializes the base class Animal
with the provided name and habitat.
• crawl() : Prints the message "The reptile is crawling"

2024-2028-CSD-B
• displayInfo() : This overridden method does the following: Calls the base class
method Animal::displayInfo() to display the name and habitat of the
reptile.

Task:
18. Implement the class structure using inheritance.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


19. Provide a simple user interface to manage and interact with the animals, allowing
the user to create animals of different types, set their attributes, and call their
respective behaviors (e.g., fly(), nurse(), etc.).

Input Format:
• The user will first choose the type of animal they wish to create: Mammal, Bird, or
Reptile.
• The user will then input the common attributes of the animal (name, habitat).
• Depending on the type of animal, additional attributes specific to the type will be
requested (e.g., for Mammals, hasFur will be requested).
• Finally, the user can invoke actions (eat(), sleep(), fly(), etc.) based on the animal
type.

Output Format:
• After creating the animal, the system should display the information about the
animal.
• When invoking actions like eat(), sleep(), and specific actions (e.g., fly(), nurse(),
crawl()), appropriate messages should be printed.

Note: Refer to the visible test cases for detailed input and output layout.
Source Code:
animalInheritance.cpp

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 323
#include <iostream>

Page No: 324


#include <string>
using namespace std;
// Base class
class Animal {
protected:
string name;

ID: 247Y1A6790
string habitat;
public:
Animal(const string& n,const string& h) : name(n),habitat(h) {}
void eat(){
cout << "The animal is eating" << endl;
}
void sleep(){
cout << "The animal is sleeping" <<endl;
}
virtual void displayInfo() const{

2024-2028-CSD-B
cout << "Name: " << name << endl;
cout << "Habitat: " << habitat << endl;
}
virtual ~Animal() {}
};
// Derived class Mammal
class Mammal :public Animal{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


private:
bool hasFur;
public:
Mammal(const string& n,const string& h,bool fur) :
Animal(n,h),hasFur(fur) {}
void nurse(){
cout << "The mammal is nursing its young" << endl;
}
void displayInfo() const override{
Animal::displayInfo();
cout << "Has Fur: " << (hasFur ? "Yes" : "No") << endl;
}
};
// Derived class Bird
class Bird :public Animal{
public:
Bird(const string& n,const string& h) : Animal(n,h) {}
void fly(){
cout << "The bird is flying" << endl;
}
void displayInfo() const override{
Animal::displayInfo();
}

Page No: 325


};
// Derived class Reptile
class Reptile :public Animal{
public:
Reptile(const string& n,const string& h) : Animal(n,h){}
void crawl(){

ID: 247Y1A6790
cout << "The retile is crawing" << endl;
}
void displayInfo() const override{
Animal:: displayInfo();
}
};

int main() {
int choice;

2024-2028-CSD-B
cout << "Choose an animal type:\n1. Mammal\n2. Bird\n3. Reptile\n";
cin >> choice;

cin.ignore(); // Clear the buffer


string name, habitat;

switch(choice) {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


case 1: { // Mammal
getline(cin, name);
getline(cin, habitat);
bool hasFur;
cin >> hasFur;
Mammal mammal(name, habitat, hasFur);
mammal.displayInfo();
cout << "Actions:\n1. Eat\n2. Sleep\n3. Nurse\nChoose an
action: ";
int action;
cin >> action;
if (action == 1) mammal.eat();
else if (action == 2) mammal.sleep();
else if (action == 3) mammal.nurse();
break;
}
case 2: { // Bird
getline(cin, name);
getline(cin, habitat);
Bird bird(name, habitat);
bird.displayInfo();
cout << "Actions:\n1. Eat\n2. Sleep\n3. Fly\nChoose an
action: ";

Page No: 326


int action;
cin >> action;
if (action == 1) bird.eat();
else if (action == 2) bird.sleep();
else if (action == 3) bird.fly();
break;

ID: 247Y1A6790
}
case 3: { // Reptile
getline(cin, name);
getline(cin, habitat);
Reptile reptile(name, habitat);
reptile.displayInfo();
cout << "Actions:\n1. Eat\n2. Sleep\n3. Crawl\nChoose an
action: ";
int action;
cin >> action;

2024-2028-CSD-B
if (action == 1) reptile.eat();
else if (action == 2) reptile.sleep();
else if (action == 3) reptile.crawl();
break;
}
default:
cout << "Invalid option" << endl;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose an animal type:
1. Mammal
2. Bird
3. Reptile
1
Lion
Forest
1
Name: Lion
Habitat: Forest

Page No: 327


Has Fur: Yes
Actions:
1. Eat
2. Sleep
3. Nurse

ID: 247Y1A6790
Choose an action:
1
The animal is eating

Test Case - 2

User Output
Choose an animal type:

2024-2028-CSD-B
1. Mammal
2. Bird
3. Reptile
2
Eagle
Mountain

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Name: Eagle
Habitat: Mountain
Actions:
1. Eat
2. Sleep
3. Fly
Choose an action:
3
The bird is flying

Test Case - 3

User Output
Choose an animal type:
1. Mammal
2. Bird
3. Reptile
3
Snake
2
Desert

1. Eat

3. Crawl
2. Sleep
Actions:
Name: Snake
Habitat: Desert

Choose an action:

The animal is sleeping

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 328
Exp. Name: Drawing Various Shapes Date: 2025-01-
S.No: 127

Page No: 329


Using Polymorphism 06

Aim:
You are required to implement an application that can draw various shapes such as Circle,
Rectangle, and Triangle using polymorphism. You will create an abstract base class Shape

ID: 247Y1A6790
with a method draw(). Then, you will implement three subclasses: Circle, Rectangle,
and Triangle. Each subclass should provide its specific implementation of the draw
method. The application should then be able to handle any shape object through the
Shape interface.

The application should accept input from the user to choose a shape and then output the
drawing command corresponding to that shape.

Class Design:
Abstract Base Class Shape:

2024-2028-CSD-B
The class will define a pure virtual method draw() which will be overridden by the
subclasses.

Derived Classes (Circle, Rectangle, Triangle):


• Circle should override draw() to print "Drawing a Circle".
• Rectangle should override draw() to print "Drawing a Rectangle".

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• Triangle should override draw() to print "Drawing a Triangle".

Polymorphism:
Your application should use a reference to the base class (Shape) to invoke the
appropriate draw() method for the specific shape object, demonstrating polymorphism.

Input Format:
The program will prompt the user to choose a shape from the following options:
• 1 for Circle
• 2 for Rectangle
• 3 for Triangle
Based on the user's choice, the program will draw the corresponding shape.

Output Format:
For each shape, the program will output a message indicating which shape is being
drawn:
• For Circle: "Drawing a Circle"
• For Rectangle: "Drawing a Rectangle"
• For Triangle: "Drawing a Triangle"
Source Code:
drawingShapes.cpp

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 330
#include <iostream>

Page No: 331


using namespace std;
// Abstract base class
class Shape {
public:
virtual void draw() =0;
virtual ~Shape() {}

ID: 247Y1A6790
};
// Circle class derived from Shape
class Circle :public Shape{
public:
void draw() override{
cout << "Drawing a Circle" << endl;
}
};
// Rectangle class derived from Shape
class Rectangle :public Shape{

2024-2028-CSD-B
public:
void draw() override{
cout << "Drawing a Rectangle" << endl;
}
};
// Triangle class derived from Shape
class Triangle :public Shape{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


public:
void draw() override{
cout << "Drawing a Triangle" <<endl;
}
};
// Function to demonstrate polymorphism
void drawShape(Shape& shape ) {
shape.draw();
}

int main() {
int choice;

// User prompt
cout << "Choose a shape to draw:" << endl;
cout << "1. Circle" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Triangle" << endl;
cin >> choice;

// Creating a shape pointer to handle polymorphism


Shape* shape = nullptr;

Page No: 332


switch(choice) {
case 1:
shape = new Circle(); // Instantiate Circle
break;
case 2:

ID: 247Y1A6790
shape = new Rectangle(); // Instantiate Rectangle
break;
case 3:
shape = new Triangle(); // Instantiate Triangle
break;
default:
cout << "Invalid choice" << endl;
return 1;
}

2024-2028-CSD-B
// Polymorphic behavior: draw the selected shape
drawShape(*shape);
return 0;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Choose a shape to draw:
1. Circle
2. Rectangle
3. Triangle
1
Drawing a Circle

Test Case - 2

User Output
Choose a shape to draw:
1. Circle
2. Rectangle
3. Triangle
4
Invalid choice

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 333
Exp. Name: Simulating Sounds of Date: 2025-01-
S.No: 128

Page No: 334


Different Animals Using Polymorphism 06

Aim:
You are tasked with writing a program that simulates the sounds of different animals. The
program should implement the concept of polymorphism by using an abstract base class

ID: 247Y1A6790
called Animal with a pure virtual function makeSound(). Three animal types are
provided: Dog, Cat, and Cow, and each animal makes a different sound. The program
should prompt the user to select one of these animals, and then the program should
print the respective sound for that animal using polymorphism.

Requirements:
Abstract Base Class Animal:
Define a class Animal that contains a pure virtual function makeSound(). This function
will be overridden by the derived classes.

2024-2028-CSD-B
Derived Classes (Dog, Cat, Cow):
Each derived class (Dog, Cat, and Cow) should inherit from Animal and implement the
makeSound() method to print the sound specific to each animal:
• Dog: prints "Woof".
• Cat: prints "Meow".
• Cow: prints "Moo".

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Input Format:
The program will prompt the user to choose one of the three animals by entering an
integer:
• 1 for Dog
• 2 for Cat
• 3 for Cow

Output Format:
The output should be the sound of the selected animal:
• For Dog, print "Woof".
• For Cat, print "Meow".
• For Cow, print "Moo".
• If the user enters an invalid choice (anything other than 1, 2, or 3), print "Invalid
choice".
Source Code:

animalSounds.cpp
#include <iostream>

Page No: 335


using namespace std;
// Abstract base class Animal
class Animal {
public:
virtual void makeSound() const=0;
virtual ~Animal() {}

ID: 247Y1A6790
};
// Dog class derived from Animal
class Dog :public Animal{
public:
void makeSound() const override{
cout << "Woof" <<endl;
}
};
// Cat class derived from Animal
class Cat:public Animal {

2024-2028-CSD-B
public:
void makeSound() const override{
cout<< "Meow" << endl;
}
};
// Cow class derived from Animal
class Cow:public Animal {

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


public:
void makeSound() const override{
cout<<"Moo"<<endl;
}
};
// Function to simulate the sound of the animal
void simulateSound(const Animal& animal) {
animal.makeSound();
}

int main() {
int choice;

// Prompting the user to choose an animal


cout << "Choose an animal to simulate its sound:" << endl;
cout << "1. Dog" << endl;
cout << "2. Cat" << endl;
cout << "3. Cow" << endl;
cin >> choice;

// Creating an object of the chosen type


Animal* animal = nullptr;

Page No: 336


// Based on the choice, create the appropriate animal object
switch(choice) {
case 1:
animal = new Dog(); // Create a Dog object
break;

ID: 247Y1A6790
case 2:
animal = new Cat(); // Create a Cat object
break;
case 3:
animal = new Cow(); // Create a Cow object
break;
default:
cout << "Invalid choice" << endl;
return 1;
}

2024-2028-CSD-B
// Simulate the sound of the chosen animal
simulateSound(*animal);
return 0;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Choose an animal to simulate its sound:
1. Dog
2. Cat
3. Cow
1
Woof

Test Case - 2

User Output
Choose an animal to simulate its sound:
1. Dog
2. Cat
4
3. Cow

Invalid choice

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 337
Exp. Name: Managing Different Types of Date: 2025-01-
S.No: 129

Page No: 338


Transportation Using Polymorphism 06

Aim:
You are tasked with creating a system that manages different types of vehicles (Car, Bus,
and Bicycle). Each vehicle should perform specific operations based on its type. Use

ID: 247Y1A6790
polymorphism to handle the operations uniformly.

Class Specifications:
Base Class Vehicle
• A pure virtual function move(int value)

Derived Classes:
Car:
• Atrribute: speed : initialized to 0
• The car should increase its speed by a specified value each time the move()

2024-2028-CSD-B
function is called.
Bus:
• Atrribute: passengers : initialized to 0
• The bus should load passengers. Each time the move() function is called, it loads
a specific number of passengers.
Bicycle:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• Atrribute: gear: initialized to 1
• The bicycle should increase its gear or resistance level each time the move()
function is called.
Polymorphism:
• The program should allow the user to choose the type of vehicle and then invoke
the respective move() operation for that vehicle, using polymorphism.

Input Format:
The user will input an integer corresponding to the type of vehicle:
• 1 for Car
• 2 for Bus
• 3 for Bicycle
After choosing the vehicle, the user will input an integer that represents the value to
operate on:
• For the Car: Input a number to increase its speed.
• For the Bus: Input a number to load passengers.
• For the Bicycle: Input a number to increase its gear.

Output Format:
After the operation is performed, print the updated status for that vehicle:
• Car: "The car is now moving at [speed] km/h"
• Bus: "The bus now has [passengers] passengers"
• Bicycle: "The bicycle is now in gear [gear]"

Page No: 339


• If the user enters an invalid choice, print "Invalid choice".
Source Code:

transportPolymorphism.cpp

ID: 247Y1A6790
2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
#include <iostream>

Page No: 340


using namespace std;
// Abstract base class Vehicle
class Vehicle {
public:
virtual void move(int value)=0;
};

ID: 247Y1A6790
// Car class derived from Vehicle
class Car:public Vehicle{
private:
int speed;
public:
Car() : speed(0) {}
void move(int value) override{
speed+=value;
cout << "The car is now moving at " << speed << " km/h" <<
endl;

2024-2028-CSD-B
}
};
// Bus class derived from Vehicle
class Bus:public Vehicle{
private:
int passengers;
public:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Bus() : passengers(0) {}
void move(int value) override{
passengers+=value;
cout << "The bus now has " << passengers <<" passengers" <<
endl;
}
};
// Bicycle class derived from Vehicle
class Bicycle:public Vehicle{
private:
int gear;
public:
Bicycle() : gear(1){}
void move(int value) override{
gear+=value;
cout << "The bicycle is now in gear "<< gear << endl;
}
};
void simulateMovement(Vehicle& vehicle,int value) {
vehicle.move(value);
}
Page No: 341
int main() {
int choice, value;

// Prompting the user to choose a vehicle


cout << "Choose a vehicle to simulate its operation:" << endl;
cout << "1. Car" << endl;

ID: 247Y1A6790
cout << "2. Bus" << endl;
cout << "3. Bicycle" << endl;
cin >> choice;

// Asking for the value to perform the operation


cout << "Enter a value for the operation: ";
cin >> value;

// Creating an object of the chosen type


Vehicle* vehicle = nullptr;

2024-2028-CSD-B
// Based on the choice, create the appropriate vehicle object
switch(choice) {
case 1:
vehicle = new Car(); // Create a Car object
break;
case 2:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


vehicle = new Bus(); // Create a Bus object
break;
case 3:
vehicle = new Bicycle(); // Create a Bicycle object
break;
default:
cout << "Invalid choice" << endl;
return 1;
}

// Simulate the operation of the chosen vehicle


simulateMovement(*vehicle, value);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1
User Output

Page No: 342


Choose a vehicle to simulate its operation:
1. Car
2. Bus
3. Bicycle
1

ID: 247Y1A6790
Enter a value for the operation:
40
The car is now moving at 40 km/h

Test Case - 2

User Output
Choose a vehicle to simulate its operation:
1. Car

2024-2028-CSD-B
2. Bus
3. Bicycle
2
Enter a value for the operation:
16
The bus now has 16 passengers

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
Choose a vehicle to simulate its operation:
1. Car
2. Bus
3. Bicycle
3
Enter a value for the operation:
1
The bicycle is now in gear 2
Exp. Name: A System for Sending
Date: 2025-01-

Page No: 343


S.No: 130 Notifications via Email, SMS, and Push
06
Notifications Using Polymorphism

Aim:

ID: 247Y1A6790
You are tasked with designing a notification system that sends notifications through
different mediums such as Email, SMS, and Push Notification. To achieve this, you should
define a base class called Notification with an abstract method send(). Each type of
notification (Email, SMS, Push) will implement its own send() method. The system will
be able to send notifications through any medium using the same interface, ensuring
polymorphism.

Program Requirements:
Base Class Notification:
• Define an abstract class Notification with a pure virtual function send(const

2024-2028-CSD-B
string& message) that all the derived classes will override.

Derived Classes (EmailNotification, SMSNotification, PushNotification):


• EmailNotification: Implements the send(const string& message)
method to simulate sending an email.
• SMSNotification: Implements the send(const string& message)
method to simulate sending an SMS.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• PushNotification: Implements the send(const string& message)
method to simulate sending a push notification.

Polymorphism:
• The system should allow sending notifications through different mediums using
the same interface. The method send() should be called on a reference or
pointer of the base class Notification.

Input Format:
The user will input an integer corresponding to the notification medium:
• 1 for Email
• 2 for SMS
• 3 for Push Notification
The user will also input the content of the message they want to send.

Output Format:
After the user inputs their choice and message, the system should send the notification
and print:
• For Email: "Email sent: [message]"
• For SMS: "SMS sent: [message]"
• For Push Notification: "Push Notification sent: [message]"
Source Code:

notifications.cpp

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 344
#include <iostream>

Page No: 345


using namespace std;
// Abstract base class Notification
class Notification {
public:
virtual void send(const string& message)=0;
virtual ~Notification() {}

ID: 247Y1A6790
};
// EmailNotification class derived from Notification
class EmailNotification:public Notification {
public:
void send(const string& message)override{
cout << "Email sent: "<< message << endl;
}
};
// SMSNotification class derived from Notification
class SMSNotification:public Notification{

2024-2028-CSD-B
public:
void send(const string& message)override{
cout << "SMS sent: " <<message<<endl;
}
};
// PushNotification class derived from Notification
class PushNotification:public Notification{

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


public:
void send(const string& message) override{
cout << "Push Notification sent: " << message <<endl;
}
};
// Function to simulate sending a notification
void sendNotification(Notification* notification,const string& message)
{
if(notification!=nullptr){
notification->send(message);
}
}

int main() {
int choice;
string message;

// Prompting the user to choose a notification medium


cout << "Choose a notification medium:" << endl;
cout << "1. Email" << endl;
cout << "2. SMS" << endl;

Page No: 346


cout << "3. Push Notification" << endl;
cin >> choice;

// Get the content of the message


cin.ignore(); // To ignore the newline character from the previous
input

ID: 247Y1A6790
//cout << "Enter your message: ";
getline(cin, message);

// Creating an object of the chosen type


Notification* notification = nullptr;

// Based on the choice, create the appropriate notification object


switch(choice) {
case 1:
notification = new EmailNotification(); // Create an

2024-2028-CSD-B
EmailNotification object
break;
case 2:
notification = new SMSNotification(); // Create an
SMSNotification object
break;
case 3:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


notification = new PushNotification(); // Create a
PushNotification object
break;
default:
cout << "Invalid choice" << endl;
return 1;
}

// Send the notification


sendNotification(notification, message);
return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose a notification medium:
1. Email
2. SMS

Page No: 347


3. Push Notification
1
Leave Approved
Email sent: Leave Approved

ID: 247Y1A6790
Test Case - 2

User Output
Choose a notification medium:
1. Email
2. SMS
3. Push Notification
2

2024-2028-CSD-B
Recharged Successfully
SMS sent: Recharged Successfully

Test Case - 3

User Output

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Choose a notification medium:
1. Email
2. SMS
3. Push Notification
3
Deal ends Today
Push Notification sent: Deal ends Today
Exp. Name: Document Editor Supporting Date: 2025-01-
S.No: 131

Page No: 348


Various Document Types 06

Aim:
You are tasked with creating a system that simulates a document editor which can handle
different types of documents such as TextDocuments, Spreadsheets, and Presentations.

ID: 247Y1A6790
The system should allow the user to save documents using their respective saving
mechanisms.
To achieve this, you need to:

Define a base class Document:


• The Document class should have a virtual function save() that will be overridden
by the derived classes to handle specific saving mechanisms for each type of
document.

Derived Classes (TextDocument, Spreadsheet, Presentation):

2024-2028-CSD-B
• TextDocument: Implements the save() method to simulate saving a text
document.
• Spreadsheet: Implements the save() method to simulate saving a spreadsheet.
• Presentation: Implements the save() method to simulate saving a
presentation.

User Input:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The user will choose the type of document they wish to save and provide a
filename. The system will then call the save() method for the selected document
type.

Input Format:
The user will input an integer to select the document type:
• 1 for TextDocument
• 2 for Spreadsheet
• 3 for Presentation
After selecting a document type, the user will input the filename for the document.

Output Format:
After the user provides the document type and filename, the system will simulate saving
the document and print the corresponding save message:
• For TextDocument: "Saving text document [filename]"
• For Spreadsheet: "Saving spreadsheet [filename]"
• For Presentation: "Saving presentation [filename]"
• If the user enters an invalid choice, print "Invalid choice".
Source Code:
typeOfDocument.cpp

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 349
#include <iostream>

Page No: 350


using namespace std;
// Base class Document with a virtual function save()
class Document {
public:
virtual void save(const string& filename)=0;
virtual ~Document() {}

ID: 247Y1A6790
};
// Derived class TextDocument
class TextDocument:public Document{
public: void save(const string& filename) override{
cout << "Saving text document " <<filename <<endl;
}
};
// Derived class Spreadsheet
class Spreadsheet:public Document{
public:

2024-2028-CSD-B
void save(const string& filename) override{
cout << "Saving spreadsheet " << filename << endl;
}
};
// Derived class Presentation
class Presentation:public Document{
public:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


void save(const string& filename) override{
cout << "Saving presentation " << filename << endl;
}
};
// Function to simulate saving a document
void saveDocument(Document* doc,const string& filename) {
if(doc!=nullptr){
doc->save(filename);
}
}

int main() {
int choice;
string filename;

// Prompt the user to choose a document type


cout << "Choose a document type to save:" << endl;
cout << "1. TextDocument" << endl;
cout << "2. Spreadsheet" << endl;
cout << "3. Presentation" << endl;
cin >> choice;
Page No: 351
// Get the filename from the user
cin.ignore(); // To ignore the newline character from previous
input
//cout << "Enter the filename: ";
getline(cin, filename);

ID: 247Y1A6790
// Create an object of the appropriate type
Document* doc = nullptr;

// Based on the user's choice, create the corresponding object


switch(choice) {
case 1:
doc = new TextDocument(); // Create a TextDocument object
break;
case 2:
doc = new Spreadsheet(); // Create a Spreadsheet object

2024-2028-CSD-B
break;
case 3:
doc = new Presentation(); // Create a Presentation object
break;
default:
cout << "Invalid choice" << endl;
return 1;

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


}

// Simulate saving the document


saveDocument(doc, filename);

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose a document type to save:
1. TextDocument
2. Spreadsheet
3. Presentation
1
Saving text document file.txt

Page No: 352


Test Case - 2

User Output
Choose a document type to save:

ID: 247Y1A6790
1. TextDocument
2. Spreadsheet
3. Presentation
2
data.xlsx
Saving spreadsheet data.xlsx

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Exp. Name: Audio Effects Processing Date: 2025-01-
S.No: 132

Page No: 353


Library 06

Aim:
You are tasked with developing a simple audio processing library that applies three basic
audio effects (Reverb, Echo, and Distortion) to a given audio signal. The audio signal is

ID: 247Y1A6790
represented as a sequence of floating-point numbers, where each number corresponds
to the amplitude of the audio at a specific point in time.

In this program, you will define an abstract base class AudioEffect with a virtual
method apply(), and three subclasses: ReverbEffect, EchoEffect, and
DistortionEffect, which will override the apply() method. Each subclass will
perform a simple operation on the audio signal. The goal is to process the audio signal by
applying these three effects in sequence: Reverb, Echo, and Distortion. After applying all
effects, you should display the original and modified audio signal.

2024-2028-CSD-B
Requirements:
• The AudioEffect class will be the abstract base class with a virtual apply()
method.
• The ReverbEffect subclass should override apply() to add 0.1f to each
sample of the audio signal.
• The EchoEffect subclass should override apply() to subtract 0.05f from each
sample of the audio signal.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• The DistortionEffect subclass should override apply() to add 0.2f to any
sample that exceeds the threshold of 0.5f.
• The program should take user input for the number of audio samples and their
respective values.
• The program should display the original and the modified audio signal after
applying all effects.

Input Format:
• The first input is the number of samples in the audio signal.
• The user provides the audio signal samples as floating-point numbers, one for
each sample.

Output Format:
• After receiving the audio samples, the original audio signal should be printed
(space-separated).
• After applying the three effects (Reverb, Echo, and Distortion) in sequence, the
modified audio signal should be printed (space-separated).
Source Code:

audioEffects.cpp
#include <iostream>

Page No: 354


#include <vector>
#include <algorithm>
using namespace std;
// Base class for all audio effects
class AudioEffect {
public:

ID: 247Y1A6790
virtual void apply(vector<float>& audioSignal)=0;
virtual ~AudioEffect() {}
};
// Subclass for Reverb effect
class ReverbEffect:public AudioEffect{
public:
void apply(vector<float>& audioSignal)override{
for(auto& sample : audioSignal){
sample+=0.1f;
}

2024-2028-CSD-B
}
};
// Subclass for Echo effect
class EchoEffect:public AudioEffect {
public:
void apply(vector<float>& audioSignal)override{
for(auto& sample : audioSignal){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


sample-=0.05f;
}
}
};
// Subclass for Distortion effect
class DistortionEffect:public AudioEffect {
public:
void apply(vector<float>& audioSignal) override{
for(auto& sample : audioSignal){
if(sample>0.5f){
sample+=0.2f;
}
}
}
};

int main() {
size_t signalSize;
//cout << "Enter the number of samples in your audio signal: ";
cin >> signalSize;
// Get the audio signal from the user

Page No: 355


vector<float> audioSignal(signalSize);
//cout << "Enter the audio signal samples (floating-point numbers,
e.g., 0.1, -0.3, etc.):" << endl;
for (size_t i = 0; i < signalSize; ++i) {
//cout << "Sample " << i + 1 << ": ";
cin >> audioSignal[i];

ID: 247Y1A6790
}

// Display the original signal


//cout << "Original audio signal: ";
for (float sample : audioSignal) {
cout << sample << " ";
}
cout << endl;

// Create instances of each effect and apply them

2024-2028-CSD-B
AudioEffect* effect1 = new ReverbEffect();
AudioEffect* effect2 = new EchoEffect();
AudioEffect* effect3 = new DistortionEffect();

// Apply each effect to the audio signal


effect1->apply(audioSignal);
effect2->apply(audioSignal);

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


effect3->apply(audioSignal);

// Display the modified signal


//cout << "Modified audio signal: ";
for (float sample : audioSignal) {
cout << sample << " ";
}
cout << endl;

return 0;
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
4
0.1
3

0.7
0.6
0.2
0.3
0.4

-0.1
User Output

-0.1 0.6 0.7


-0.05 0.85 0.95
0.1 0.4 0.3 0.2
0.15 0.45 0.35 0.25

Test Case - 2

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 356
Exp. Name: Character Attack Simulation Date: 2025-01-
S.No: 133

Page No: 357


Using Virtual Functions 06

Aim:
You are tasked with creating a simple simulation program for an RPG-style game. The
game includes different types of characters, each having a specific type of attack. The

ID: 247Y1A6790
goal of the simulation is to model the attack and how it affects the health of the character
performing the attack.

Requirements:

Base Class Character:


• Attribute health (int): This protected member variable holds the health points
of the character, representing its vitality. The default value is set to 100.
• Constructor Character(): This default constructor initializes the character's
health to 100.

2024-2028-CSD-B
• Virtual function attack(): This function can be overridden by derived classes to
provide specific attack behavior. By default, it outputs "Character attacks!".
• getHealth() const: This function returns the current health of the character,
allowing access to the health attribute.
• decreaseHealth(int amount):This function decreases the character's health
by a specified amount. It ensures that health does not fall below zero.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


You are required to define the following derived character classes:

Warrior: A character with high strength that attacks using a sword.


• Attribute strength (int): holds the warrior's strength, which determines the
damage dealt during an attack.
• Constructor Warrior(int s): This constructor initializes a Warrior object with
the specified strength s.
• Override of the attack() function: This overridden method calculates the
damage based on the warrior's strength. Damage Formula:
Damage = Strength ∗ 10

Mage: A character with high intelligence who casts powerful spells. The damage dealt by
the Mage depends on their intelligence.
• Attribute intelligence (int): holds the mage's intelligence, which
determines the damage dealt during an attack.
• Constructor Mage(int i): This constructor initializes a Mage object with the
specified intelligence i.
• Override of the attack() function: This overridden method calculates the
damage based on the mage's intelligence. Damage Formula:
Damage = I ntelligence ∗ 8
Archer: A character that uses arrows to attack. The damage dealt by the Archer is fixed

Page No: 358


per arrow, and they lose arrows with each attack.
• Attribute arrows (int): holds the number of arrows available to the archer.
• Constructor Archer(int a): This constructor initializes an Archer object with
the specified number of arrows a.
• Override of the attack() function: This overridden method checks if the archer

ID: 247Y1A6790
has arrows available. If arrows are available, it calculates the damage using the
Damage Formula: Damage = 6 ∗ N umber of Arrows (Each arrow deals 6
points of damage)

Characteristics:
• Each character starts with an initial health of 100 points.
• After each attack, the health of the character performing the attack decreases by
the damage dealt.
• The Archer has a limited number of arrows, and they lose 1 arrow after each attack.

2024-2028-CSD-B
Input Format:
The user will first choose a character by entering a number from 1 to 3:
• 1 for Warrior
• 2 for Mage
• 3 for Archer
Based on the selected character, the user will input the relevant attribute:
• Warrior: Enter the Warrior's strength.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


• Mage: Enter the Mage's intelligence.
• Archer: Enter the number of arrows the Archer has.

Output Format:
• Display the damage dealt by the attack.
• After the attack, show the remaining health of the character (starting at 100
points).
Source Code:

characterSimulation.cpp
#include <iostream>

Page No: 359


using namespace std;
// Base class Character
class Character {
protected:
int health;
public:

ID: 247Y1A6790
Character():health(100){}
virtual void attack(){
cout << "Character attacks!" << endl;
}
void decreaseHealth(int amount){
health-=amount;
if(health<0){
health=0;
}
}

2024-2028-CSD-B
int getHealth() const{
return health;
}
};
// Derived class Warrior
class Warrior:public Character {
private:

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int strength;
public:
Warrior(int s): strength(s){}
void attack() override{
int damage=strength*10;
cout<<damage<<endl;
cout<<100-damage<<endl;
decreaseHealth(damage);
}
};
// Derived class Mage
class Mage:public Character {
private:
int intelligence;
public:
Mage(int i) : intelligence(i){}
void attack() override{
int damage=intelligence* 8;
cout<< damage << endl;
cout<<100-damage<<endl;
decreaseHealth(damage);
}
};

Page No: 360


// Derived class Archer
class Archer:public Character {
private:
int arrows;
public:
Archer(int a):arrows(a){}

ID: 247Y1A6790
void attack() override{
if(arrows>0){
int damage=arrows*6;
arrows--;
cout<<damage<<endl;
cout<<100-damage<<endl;
decreaseHealth(damage);
}
else{
cout << "No arrows left!" <<endl;

2024-2028-CSD-B
}
}
};
void performAttack(Character* character) {
character->attack();
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


int main() {
int choice;
int strength, intelligence, arrows;

//cout << "Welcome to the Character Attack Simulator!" << endl;


cout << "Choose a character to attack:" << endl;
cout << "1. Warrior" << endl;
cout << "2. Mage" << endl;
cout << "3. Archer" << endl;
cin >> choice;

// Collect user input for attributes based on character choice


if (choice == 1) {
//cout << "Enter Warrior's strength: ";
cin >> strength;

Warrior warrior(strength);
performAttack(&warrior);
}
else if (choice == 2) {
//cout << "Enter Mage's intelligence: ";
cin >> intelligence;

Page No: 361


Mage mage(intelligence);
performAttack(&mage);
}
else if (choice == 3) {
//cout << "Enter Archer's number of arrows: ";

ID: 247Y1A6790
cin >> arrows;

Archer archer(arrows);
performAttack(&archer);
}
else {
cout << "Invalid choice" << endl;
}

return 0;

2024-2028-CSD-B
}

Execution Results - All test cases have succeeded!


Test Case - 1

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


User Output
Choose a character to attack:
1. Warrior
2. Mage
3. Archer
1
3
30
70

Test Case - 2

User Output
Choose a character to attack:
1. Warrior
2. Mage
3. Archer
5
3

70
30
20
80
10

2. Mage
3. Archer
1. Warrior
User Output
Choose a character to attack:
Test Case - 3

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 362
Exp. Name: File Operations with Date: 2025-01-
S.No: 134

Page No: 363


Exception Handling in C++ 06

Aim:
You are required to implement a C++ program that reads data from a file. The program
must handle errors that might occur when the file does not exist or when the application

ID: 247Y1A6790
lacks permissions to open the file. Use exception handling (try-catch blocks) to handle
these specific exceptions.

File Reading:
• The user will input the name of a file they wish to read.
• The program should attempt to open the file and read its contents line by line.

Exception Handling:
• If the file does not exist or the application lacks the necessary permissions to read
the file, the program should print an error message: "Error: File does not exist or

2024-2028-CSD-B
cannot be opened".
• If the file is successfully opened and read, the program should print its contents
line by line.

Input Format:
• The program will first ask the user to input the file name they wish to read.

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Output Format:
• If the file is opened and read successfully, print its contents line by line.
• If the file cannot be opened due to non-existence or permission issues, print:
"Error: File does not exist or cannot be opened".
Source Code:

fileExceptions.cpp
#include<iostream>

Page No: 364


#include<string>
#include<fstream>
#include<stdexcept>
using namespace std;
int main(){
string filename;

ID: 247Y1A6790
cin >> filename;
try{
ifstream file(filename);
if(!file.is_open()){
throw runtime_error("File does not exist or cannot be opened");
}
string line;
while(getline(file,line)){
cout << line << endl;
}

2024-2028-CSD-B
file.close();
}
catch(const runtime_error& e){
cout << "Error: " << e.what() << endl;
}
return 0;
}

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


file1.txt

Hello
World

file2.txt

How
Are
You

demo.txt

Programming in C++
Execution Results - All test cases have succeeded!

Page No: 365


Test Case - 1

User Output
file1.txt

ID: 247Y1A6790
Hello
World

Test Case - 2

User Output
demo1.txt
Error: File does not exist or cannot be opened

2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
Exp. Name: E-Commerce Checkout Date: 2025-01-
S.No: 135

Page No: 366


Process with Exception Handling 06

Aim:
You are tasked with implementing the checkout process for an e-commerce application.
The system should process user orders and handle errors such as invalid payment details,

ID: 247Y1A6790
out-of-stock items, and delivery address issues. The program should use exception
handling to manage these errors effectively.

Order Details:
• The user places an order by selecting items and providing payment and delivery
details.
• Each order has a set of items, a payment method, and a delivery address.

Exception Handling:
• Invalid Payment Details: If the user enters invalid payment details (e.g., incorrect

2024-2028-CSD-B
card number or expired card), the system should throw an exception and print an
appropriate error message.
• Out-of-Stock Items: If the user attempts to purchase an item that is out of stock,
the system should throw an exception and print an error message indicating that
the item is unavailable.
• Invalid Delivery Address: If the user enters an invalid delivery address (e.g.,
incomplete or incorrect address), the system should throw an exception and notify

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


the user.

Input Format:
The user will enter the number of items they wish to purchase.
For each item, the user will provide:
• Item name
• Quantity
• Availability (in stock - 0 or out of stock - 1)
The user will also provide:
• Payment details (e.g., card number)
• Delivery address (valid or invalid)

Output Format:
If the checkout process is successful, print a message: "Order processed successfully".
If an error occurs during the process, print an appropriate error message:
• "Error: Invalid payment details".
• "Error: Item out of stock".
• "Error: Invalid delivery address".

Constraints:
• Assume the card number must be 16 digits long for a valid payment.
• If any item in the order is out of stock, the order should not be processed, and the
user should be notified immediately.

Page No: 367


• A valid delivery address should be a non-empty string with at least 10 characters.
Source Code:

checkout.cpp

ID: 247Y1A6790
2024-2028-CSD-B
Marri Laxman Reddy Institute of Technology and Management (Autonomous)
#include <iostream>

Page No: 368


#include <string>
#include <stdexcept>
using namespace std;
class InvalidPaymentException : public std::runtime_error{
public:
InvalidPaymentException(): runtime_error("Error: Invalid payment

ID: 247Y1A6790
details"){}
};
class OutOfStockException : public std::runtime_error {
public:
OutOfStockException():runtime_error("Error: Item out of stock"){}
};
class InvalidAddressException : public std::runtime_error {
public:
InvalidAddressException():runtime_error("Error: Invalid delivery
address"){}

2024-2028-CSD-B
};
void validatePayment(const string& cardNumber){
if(cardNumber.length()!=16){
throw InvalidPaymentException();
}
}
void validateAddress(const string& address){

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


if(address.length() <10){
throw InvalidAddressException();
}
}
int main() {
int numItems;
cin >> numItems;

string itemName;
int quantity;
string availability;
bool allItemsInStock = true;

// Collect item details.

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


cout << "Item " << i + 1 << ":\n";
//cout << " Name: ";
cin >> itemName;
//cout << " Quantity: ";
cin >> quantity;
//cout << " Availability (in stock / out of stock): ";
cin >> availability;

Page No: 369


// If any item is out of stock, throw exception
if (availability == "1") {
allItemsInStock = false;
}
}

ID: 247Y1A6790
// Check if all items are in stock
try {
if(!allItemsInStock){
throw OutOfStockException();
}
// Collect payment details
string cardNumber;
cin >> cardNumber;
// Validate payment details
validatePayment(cardNumber);

2024-2028-CSD-B
// Collect delivery address
string deliveryAddress;
cin.ignore(); // To clear the input buffer
getline(cin, deliveryAddress);
// Validate delivery address
validateAddress(deliveryAddress);
// If no exceptions occurred, process the order

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


cout << "Order processed successfully" << endl;
} catch (const InvalidPaymentException& e ) {
cout << e.what() << endl;
} catch (const OutOfStockException& e ) {
cout << e.what() << endl;
} catch (const InvalidAddressException& e ) {
cout<< e.what() << endl;
}
return 0;
};

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
1
Item 1:
Laptop
2

Page No: 370


1
Error: Item out of stock

Test Case - 2

ID: 247Y1A6790
User Output
2
Item 1:
Mouse
1
0
Item 2:
Umbrella

2024-2028-CSD-B
2
0
1234567890
Error: Invalid payment details

Marri Laxman Reddy Institute of Technology and Management (Autonomous)


Test Case - 3

User Output
1
Item 1:
Handbag
1
0
1234567890112233
india
Error: Invalid delivery address

Test Case - 4

User Output
1
Item 1:
Shoes
0
1

gandhiNagar,Delhi
0987654321234567

Order processed successfully

Marri Laxman Reddy Institute of Technology and Management (Autonomous) 2024-2028-CSD-B ID: 247Y1A6790 Page No: 371

You might also like