0% found this document useful (0 votes)
10 views57 pages

Week 7 (Lab PRGS)

The document outlines a coding lab focused on function overloading, consisting of four questions that require implementing various functionalities such as finding minimum values, unit conversions, shopping cart calculations, and speed calculations. Each question includes specific input and output formats, constraints, and sample cases to guide the implementation. The lab emphasizes the use of function overloading in C++ to achieve the desired results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views57 pages

Week 7 (Lab PRGS)

The document outlines a coding lab focused on function overloading, consisting of four questions that require implementing various functionalities such as finding minimum values, unit conversions, shopping cart calculations, and speed calculations. Each question includes specific input and output formats, constraints, and sample cases to guide the implementation. The lab emphasizes the use of function overloading in C++ to achieve the desired results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

VIT C_Structured and OOP_Lab 7_COD_Function Overloading

Test Summary
 No. of Sections: 1
 No. of Questions: 4
 Total Duration: 30 min
Section 1 - Coding
Section Summary
 No. of Questions: 4
 Duration: 30 min
Additional Instructions:
None
Q1.
Problem Statement

Vamsi is a young and curious student who is eager to learn about finding the minimum
number among a set of integers and double values. He needs a program to find the
minimum number from a given set of values.

Help him solve the program by overloading the function named findMin.
Input Format
The first line of input consists of three space-separated integers.
The second line consists of three space-separated double values.
Output Format
The first line of output prints "Minimum integer: " followed by the minimum integer among
the given values.
The second line prints "Minimum double-point value: " followed by the minimum double-
point number among the given values, rounded off to two decimal places.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ integers ≤ 1000
0.00 ≤ double-point values ≤ 1000.00
Sample Input Sample Output
837
19.4 10.5 0.8
Minimum integer: 3
Minimum double-point value: 0.80
Sample Input Sample Output
435 768 346
3.531 4.561 7.89
Minimum integer: 346
Minimum double-point value: 3.53
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement
Teju is working on a unit converter application that can convert lengths from millimetres to
centimetres and kilometres. The application uses function overloading to handle the
different unit types.

She wants to implement a UnitConverter class that contains two overloaded functions for
conversion:
1. double convert(double millimetres) - If the unit type is 1, convert the value to
centimetres.
2. double convert(int unitType, double value) - If the unit type is 2, convert the value to
kilometres.

Assist Teju in completing the converter application.


Input Format
The first line of input consists of an integer unitType (1 or 2) representing the unit type.
The second line consists of a double value N, representing the value in millimetres to be
converted.
Output Format
If the unit type is 1, print "X cm" where X is a double value, rounded off to two decimal
places.
If the unit type is 2, print "Y km" where Y is a double value, rounded off to two decimal
places.
If the unit type is not valid, print "Invalid unit type!"

Refer to the sample output for formatting specifications.


Constraints
1.00 ≤ N ≤ 1000000.00
Sample Input Sample Output
1
100.00
10.00 cm
Sample Input Sample Output
2
541456.00
0.54 km
Sample Input Sample Output
3
Invalid unit type!
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

You are creating a shopping cart for an e-commerce website. Implement overloaded
functions called calculateTotalPrice that can calculate the total price of different types of
items, such as a single item, multiple items, or items with discounts. Each overloaded
function should take the required parameters and return the calculated total price.
1. Calculate the total price for a single item without quantity or discounts.
2. Calculate the total price for multiple items in quantity without any discounts.
3. Calculate the total price for multiple items with quantity and a discount percentage.
Input Format
The user should enter an integer corresponding to the desired option (1, 2, 3, or 4).
If the choice is 1, the input consists of the price of the item, separated by a space.
If the choice is 2, the input consists of the price of the item and the quantity, separated by a
space.
If the choice is 3, the program consists of the price of the item, the quantity, and the
discount percentage, separated by a space.
If the choice is 4, the program exits.
If the choice is other than 1, 2, 3, or 4, it is considered an invalid choice.
Output Format
For the choices 1, 2, and 3, the output displays the calculated total price as a floating-point
number with two decimal places.
If the choice is 4, the program exits.
If the choice is invalid, the output displays "Invalid choice".
The output will be displayed on a new line.

Refer to the sample outputs for the formatting specifications.


Constraints
1 <= choice <= 4
0 <= Quantity <= 3000
0.0 <= Price <= 3000.0
Sample Input Sample Output
1 10.5
2 102.25 3
3 100 10 10
4
10.50
306.75
900.00
Sample Input Sample Output
2 150 2
5
4
300.00
Invalid choice
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

You are designing a traffic simulator. Implement overloaded functions called calculateSpeed
that can calculate different speeds, such as the speed of a car, the speed of a train, and the
speed of a plane. Each overloaded function should take the required inputs and return the
calculated speed.

Formula:
speed = distance/time
speed = (distance/time) + acceleration*time

Example

Input:
100.5
10
5.5
6.6

Output:
10.05
65.05
76.05
Input Format
The first line of input consists of the distance (in meters) as a double value.
The second line of input consists of the time (in seconds) as a double value.
The third line of input consists of the acceleration (in m/s2) of the train as a double value.
The last line of input consists of the acceleration (in m/s2) of the plane as a double value.
Output Format
The first line of output prints the speed of the car (m/s) rounded off to two decimal places.
The second line of output prints the speed of the train (m/s) rounded off to two decimal
places.
The last line of output prints the speed of the plane (m/s) rounded off to two decimal places.

Refer to the sample output for the formatting specifications.


Constraints
1.0 < distance < 2500.0
1.0 < time < 60.0
1.0 < accelerations of train and plane < 50.0
Sample Input Sample Output
100.5
10.0
5.5
6.6
10.05
65.05
76.05
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1Hidden Test CaseInputOutput
67 43 90
12.5 76.5 9.4
Minimum integer: 43
Minimum double-point value: 9.40
Weightage - 15InputOutput
852
9.0 4.0 3.7
Minimum integer: 2
Minimum double-point value: 3.70
Weightage - 10InputOutput
12 6 10
10.9 76.3 8.2
Minimum integer: 6
Minimum double-point value: 8.20
Weightage - 10InputOutput
100 400 1000
4.2 786.4 293.9
Minimum integer: 100
Minimum double-point value: 4.20
Weightage - 25InputOutput
123 765 364
34.8 89.3 756.0
Minimum integer: 123
Minimum double-point value: 34.80
Weightage - 15InputOutput
987 989 999
234.5 6.7 8.94
Minimum integer: 987
Minimum double-point value: 6.70
Weightage - 25Sample InputSample Output
837
19.4 10.5 0.8
Minimum integer: 3
Minimum double-point value: 0.80
Sample InputSample Output
435 768 346
3.531 4.561 7.89
Minimum integer: 346
Minimum double-point value: 3.53
Solution
#include <iostream>
#include <iomanip>
using namespace std;

int findMin(int num1, int num2, int num3) {


int minNum = num1;
if (num2 < minNum) {
minNum = num2;
}
if (num3 < minNum) {
minNum = num3;
}
return minNum;
}

double findMin(double num1, double num2, double num3) {


double minNum = num1;
if (num2 < minNum) {
minNum = num2;
}
if (num3 < minNum) {
minNum = num3;
}
return minNum;
}

int main() {
int int1, int2, int3;
double double1, double2, double3;

cin >> int1 >> int2 >> int3;


cin >> double1 >> double2 >> double3;

int minInt = findMin(int1, int2, int3);


cout << "Minimum integer: " << minInt << endl;

double minDouble = findMin(double1, double2, double3);


cout << fixed << setprecision(2);
cout << "Minimum double-point value: " << minDouble ;

return 0;
}
Q2Hidden Test CaseInputOutput
2
12000.00
0.01 km
Weightage - 10InputOutput
6
Invalid unit type!
Weightage - 10InputOutput
1
9000.00
900.00 cm
Weightage - 15InputOutput
2
18976.00
0.02 km
Weightage - 15InputOutput
1
7869.00
786.90 cm
Weightage - 25InputOutput
2
10000.00
0.01 km
Weightage - 25Sample InputSample Output
1
100.00
10.00 cm
Sample InputSample Output
2
541456.00
0.54 km
Sample InputSample Output
3
Invalid unit type!
Solution
#include <iostream>
#include <iomanip>
using namespace std;

class UnitConverter {
public:
double convert(double millimeters) {
return millimeters / 10.0;
}

double convert(int unitType, double value) {


if (unitType == 2) {
return value / 1000000.0;
}
}
};

int main() {
UnitConverter converter;

double value;
int unitType;

cin >> unitType;


cin >> value;

double result;

if (unitType == 1) {
result = converter.convert(value);
} else if (unitType == 2) {
result = converter.convert(unitType, value);
} else {
result = 0.0;
cout << "Invalid unit type!" ;
}

if (result != 0.0) {
if (unitType == 1) {
cout << fixed << setprecision(2) << result << " cm";
} else if (unitType == 2) {
cout << fixed << setprecision(2) << result << " km" ;
}
}

return 0;
}
Q3Hidden Test CaseInputOutput
1 150.50
1 190.50
2 500 6
4
150.50
190.50
3000.00
Weightage - 20InputOutput
2 504.50 7
6
1 200
4
3531.50
Invalid choice
200.00
Weightage - 20InputOutput
3 1547.50 2 10
2 2500 5
8
4
2785.50
12500.00
Invalid choice
Weightage - 25InputOutput
3 1310 13 10
2 457 3
3 600 57 50
2 256 3
1 2578
8
1 250
4
15327.00
1371.00
17100.00
768.00
2578.00
Invalid choice
250.00
Weightage - 35Sample InputSample Output
1 10.5
2 102.25 3
3 100 10 10
4
10.50
306.75
900.00
Sample InputSample Output
2 150 2
5
4
300.00
Invalid choice
Solution
#include <iostream>
#include <iomanip>
using namespace std;
double calculateTotalPrice(double price){
return price;
}

double calculateTotalPrice(double price, int quantity){


return price * quantity;
}

double calculateTotalPrice(double price, int quantity, double discountPercentage){


double discountedPrice = price * (1 - discountPercentage / 100);
return discountedPrice * quantity;
}

int main(){
int choice;
double price, total;
int quantity;
double discountPercentage;
do {
cin >> choice;

switch (choice) {
case 1:
cin >> price;
total = calculateTotalPrice(price);
cout << fixed << setprecision(2) << total << "\n";
break;

case 2:
cin >> price;
cin >> quantity;
total = calculateTotalPrice(price, quantity);
cout << fixed << setprecision(2) << total << "\n";
break;

case 3:
cin >> price;
cin >> quantity;
cin >> discountPercentage;
total = calculateTotalPrice(price, quantity, discountPercentage);
cout << fixed << setprecision(2) << total << "\n";

break;

case 4:
break;

default:
cout << "Invalid choice\n";
break;
}
} while (choice != 4);

return 0;
}
Q4Hidden Test CaseInputOutput
123.45
10.12
5.67
7.5
12.20
69.58
88.10
Weightage - 20InputOutput
567.89
20.23
10.11
15.5
28.07
232.60
341.64
Weightage - 20InputOutput
1090.12
30.34
15.16
15.15
35.93
495.88
495.58
Weightage - 25InputOutput
2134.56
50.56
25.18
50
42.22
1315.32
2570.22
Weightage - 35Sample InputSample Output
100.5
10.0
5.5
6.6
10.05
65.05
76.05
Solution
#include <iostream>
#include <iomanip>
using namespace std;

double calculateSpeed(double distance, double time) {


return distance / time;
}

double calculateSpeed(double distance, double time, double acceleration) {


return (distance / time) + acceleration * time;
}

int main() {
double distance;
double time;
double acceleration;

cin >> distance;


cin >> time;

double carSpeed = calculateSpeed(distance, time);


cout << fixed << setprecision(2) << carSpeed << endl;

cin >> acceleration;


double trainSpeed = calculateSpeed(distance, time, acceleration);
cout << fixed << setprecision(2) << trainSpeed << endl;

cin >> acceleration;


double planeSpeed = calculateSpeed(distance, time, acceleration);
cout << fixed << setprecision(2) << planeSpeed;

return 0;
}

VIT C_Structured and OOP_Lab 7_COD_Operator Overloading


Test Summary
 No. of Sections: 1
 No. of Questions: 4
 Total Duration: 30 min
Section 1 - Coding
Section Summary
 No. of Questions: 4
 Duration: 30 min
Additional Instructions:
None
Q1.
Problem Statement

Implement a Fraction class that represents a fraction with a numerator and a denominator.
Overload the '+' operator to add two fractions and return the result as a simplified fraction.

Function Specifications: Fraction operator+(const Fraction& other) const


Input Format
The input consists of two lines.
Each line contains two integers separated by a space.
The first line represents the numerator and denominator of the first fraction.
The second line represents the numerator and denominator of the second fraction.
Output Format
The output displays the sum of the fractions of the given input as simplified values.
Sample Input Sample Output
12
34
5/4
Sample Input Sample Output
56
13
7/6
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

John is driving a car with an initial velocity (in m/s) that suddenly accelerates at a constant
rate (in m/s2) for a certain time (in seconds). He wants to write a program that calculates and
displays the final velocity of the car.

Help John calculate the final velocity by overloading the * operator in the Acceleration class.

Formula: Final velocity = Initial velocity + (Acceleration * time)


Input Format
The input consists of three space-separated float values:
1. Initial velocity (in m/s)
2. Acceleration (in m/s2)
3. Time (in s)
Output Format
The output displays a float value representing the final velocity followed by " m/s", rounded
off to one decimal place.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1.0 ≤ Initial velocity ≤ 500.0
1.0 ≤ Acceleration ≤ 50.0
1.0 ≤ Time ≤ 50.0
Sample Input Sample Output
10.3 5.0 2.1
20.8 m/s
Sample Input Sample Output
410.2 9.8 4.5
454.3 m/s
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

Create a class Time to represent the departure time of a train, initialized with hours and
minutes. Overload the pre-increment operator ++ to advance the departure time by one
minute. Display the original and updated departure times.
Note: The time is represented in 24-hour format.
Input Format
The input consists of two space-separated integers, hours (h) and minutes (m) representing
the departure time of the train.
Output Format
The first line of output prints the original departure time and the second line prints the
updated departure time.
The time is printed in the format: [hours]h [minutes]m.

Refer to the sample output for formatting specifications.


Constraints
0 ≤ h ≤ 23
0 ≤ m ≤ 59
Sample Input Sample Output
11 57
11h 57m
11h 58m
Sample Input Sample Output
13 5
13h 5m
13h 6m
Sample Input Sample Output
23 59
23h 59m
0h 0m
Sample Input Sample Output
0 59
0h 59m
1h 0m
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

Maria is developing a program to manage student records, with a specific focus on weight
tracking. She has created a class named Student that represents student information and
allows for the incrementing (++) of a student's weight by 1 kg through operator overloading
with the friend function named operator.

Assist her in completing the program.


Input Format
The first line of input consists of an integer, representing the student's ID.
The second line consists of a double-point value, representing the initial weight of the
student.
Output Format
The first line of output prints the student ID and initial weight of the student.
The second line prints the student ID and the weight of the student after incrementing.
Round off the weights to two decimal places.
Refer to the sample output for formatting specifications.
Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ Student ID ≤ 1000
1.0 ≤ initial Weight ≤ 100.0
Sample Input Sample Output
101
34.8
101 34.80
101 35.80
Sample Input Sample Output
103
78.987
103 78.99
103 79.99
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1Hidden Test CaseInputOutput
25
35
1/1
Weightage - 10InputOutput
78
56
41/24
Weightage - 20InputOutput
11 9
37
104/63
Weightage - 20InputOutput
19 23
7 11
370/253
Weightage - 25InputOutput
13 17
5 19
332/323
Weightage - 25Sample InputSample Output
12
34
5/4
Sample InputSample Output
56
13
7/6
Solution
#include <iostream>

class Fraction {
private:
int numerator;
int denominator;

public:
Fraction(int num = 0, int denom = 1) : numerator(num), denominator(denom) {}

Fraction operator+(const Fraction& other) const {


int num = numerator * other.denominator + other.numerator * denominator;
int denom = denominator * other.denominator;
return Fraction(num, denom);
}

Fraction simplify() const {


int gcd = computeGCD(numerator, denominator);
return Fraction(numerator / gcd, denominator / gcd);
}

int computeGCD(int a, int b) const {


if (b == 0)
return a;
return computeGCD(b, a % b);
}

friend std::ostream& operator<<(std::ostream& os, const Fraction& fraction) {


os << fraction.numerator << "/" << fraction.denominator;
return os;
}
};

int main() {
int num1, denom1, num2, denom2;

std::cin >> num1 >> denom1;


std::cin >> num2 >> denom2;

Fraction f1(num1, denom1);


Fraction f2(num2, denom2);

Fraction sum = f1 + f2;


Fraction simplifiedSum = sum.simplify();

std::cout << simplifiedSum << std::endl;


return 0;
}
Q2Hidden Test CaseInputOutput
12.0 3.5 4.2
26.7 m/s
Weightage - 10InputOutput
9.3 7.2 3.3
33.1 m/s
Weightage - 10InputOutput
498.5 48.3 10.5
1005.7 m/s
Weightage - 25InputOutput
15.5 9.8 48.7
492.8 m/s
Weightage - 15InputOutput
450.8 45.9 10.0
909.8 m/s
Weightage - 25InputOutput
100.0 10.5 9.9
203.9 m/s
Weightage - 15Sample InputSample Output
10.3 5.0 2.1
20.8 m/s
Sample InputSample Output
410.2 9.8 4.5
454.3 m/s
Solution
#include <iostream>
#include <iomanip>
using namespace std;

class Acceleration {
public:
float acceleration;

Acceleration(float val) {
acceleration = val;
}

Acceleration operator*(float t) {
Acceleration result(acceleration * t);
return result;
}
};
int main() {
float iv, av, t;
cin >> iv >> av >> t;

Acceleration obj(av);
Acceleration m = obj * t;
float a = m.acceleration;
float fv = iv + a;

cout << fixed << setprecision(1) << fv << " m/s";


return 0;
}
Q3Hidden Test CaseInputOutput
10 10
10h 10m
10h 11m
Weightage - 10InputOutput
6 39
6h 39m
6h 40m
Weightage - 10InputOutput
15 15
15h 15m
15h 16m
Weightage - 15InputOutput
22 59
22h 59m
23h 0m
Weightage - 25InputOutput
16 55
16h 55m
16h 56m
Weightage - 15InputOutput
12 59
12h 59m
13h 0m
Weightage - 25Sample InputSample Output
11 57
11h 57m
11h 58m
Sample InputSample Output
13 5
13h 5m
13h 6m
Sample InputSample Output
23 59
23h 59m
0h 0m
Sample InputSample Output
0 59
0h 59m
1h 0m
Solution
#include <iostream>
using namespace std;

class Time {
public:
int hours;
int minutes;

Time(int h, int m){


hours = h;
minutes = m;
}

void display() {
cout << hours << "h " << minutes << "m";
}

Time operator++() {
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}

if (hours == 24) {
hours = 0;
}

return Time(hours, minutes);


}
};

int main() {
int hr, min;
cin >> hr >> min;

Time t(hr, min);


t.display();
cout << endl;

t = ++t;
t.display();

return 0;
}
Q4Hidden Test CaseInputOutput
201
34.5
201 34.50
201 35.50
Weightage - 10InputOutput
202
45.768
202 45.77
202 46.77
Weightage - 10InputOutput
301
56.8970
301 56.90
301 57.90
Weightage - 15InputOutput
301
78.90
301 78.90
301 79.90
Weightage - 15InputOutput
701
89.836
701 89.84
701 90.84
Weightage - 25InputOutput
701
98.84
701 98.84
701 99.84
Weightage - 25Sample InputSample Output
101
34.8
101 34.80
101 35.80
Sample InputSample Output
103
78.987
103 78.99
103 79.99
Solution
#include <iostream>
#include <iomanip>
using namespace std;

class Student {
private:
int studentID;
double weight;

public:
Student(int id, double w) {
studentID = id;
weight = w;
}

void displayStudent() {
cout << studentID << " " << fixed << setprecision(2) << weight << endl;
}

friend void operator++(Student& student);


};

void operator++(Student& student) {


student.weight++;
}

int main() {
int studentID;
double initialWeight;

cin >> studentID;


cin >> initialWeight;

Student student(studentID, initialWeight);

student.displayStudent();
++student;

student.displayStudent();

return 0;
}
VIT C_Structured and OOP_Lab 7_COD_Virtual Functions
Test Summary
 No. of Sections: 1
 No. of Questions: 4
 Total Duration: 30 min
Section 1 - Coding
Section Summary
 No. of Questions: 4
 Duration: 30 min
Additional Instructions:
None
Q1.
Problem Statement

Renu works for a retail store that sells two types of items: wooden items and electronics.
The store needs a program to calculate the total amount for a customer's purchase based on
their choice of item type and the quantity or cost of the item(s).

Create a base class, ItemType, with one virtual function.


virtual double calculateAmount()

Create a class called wooden that extends ItemType with a number of items and cost as its
private attributes. Obtain the data members and override the virtual function.
amount = number of items * cost

Create a class for electronics that extends ItemType with cost as its private attribute. Obtain
the data member and override the virtual function.
amount = 80% of the amount (20% discount)

In the main method, obtain a choice.


If the choice is 1, create an object for the wooden class and call the method.
If the choice is 2, create an object for the electronics class and call the method.
Input Format
The first line of input consists of an integer, choice (1 for Wooden, 2 for Electronics).
If choice is 1 (Wooden), the second line consists of two values, an integer noOfItems
representing the number of items
and a floating-point number cost representing the cost per item, separated by a space.
If choice is 2 (for Electronics items), a floating-point number cost is expected, representing
the cost of the Electronics item.
Output Format
The program calculates the total amount for the chosen item type based on the given input.
It then prints the calculated amount with exactly two decimal places.
If the input choice is not 1 or 2, the program will print "Invalid choice."
Refer to the sample output for the formatting specifications.
Constraints
1 <= noOfItems <= 103
0 < cost <= 105
Sample Input Sample Output
1
5 10.50
52.50
Sample Input Sample Output
2
100.50
80.40
Sample Input Sample Output
3
Invalid choice.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

Imagine you are creating a SleepTracker program that demonstrates the use of inheritance
and virtual functions. The program helps users analyze their sleep patterns, distinguishing
between weekday and weekend sleep durations.

Implement a base class called SleepTracker with attributes for bedtime and wakeup times
and virtual functions for input and duration calculation.

Derive two subclasses, WeekdaySleep and WeekendSleep, inheriting from SleepTracker.


Override the virtual functions for specific behavior on weekdays and weekends.
Input Format
The first line consists of four space-separated integers, representing the bedtime hour,
minute, wakeup hour, and minute for a weekday.
The second line consists of four space-separated integers, representing the bedtime hour,
minute, wakeup hour, and minute for a weekend.
Output Format
The first two lines are in the format "Weekday: Xh Ym" and "Weekend: Xh Ym", where:
 X is the number of hours.
 Y is the number of minutes.
The third line is a statement comparing the sleep durations:
 If the user slept more on weekdays, it outputs: "User slept more on weekdays."
 If the user slept more on the weekend, it outputs: "User slept more on the
weekend."
 If the user slept the same amount on weekdays and the weekend, it outputs: "User
slept the same amount on weekdays and the weekend."

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
00 ≤ weekday & weekend bedtime hour ≤ 24
00 ≤ weekday & weekend bedtime minutes ≤ 59
00 ≤ weekday & weekend wakeup hour ≤ 24
00 ≤ weekday & weekend wakeup minutes ≤ 59
Sample Input Sample Output
22 50 07 32
20 54 10 19
Weekday: 8h 42m
Weekend: 13h 25m
User slept more on the weekend.
Sample Input Sample Output
22 00 06 05
23 00 06 05
Weekday: 8h 5m
Weekend: 7h 5m
User slept more on weekdays.
Sample Input Sample Output
22 00 06 00
21 00 05 00
Weekday: 8h 0m
Weekend: 8h 0m
User slept the same amount on weekdays and weekend.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

Create a program that manages student information and grades for two types of students:
Undergraduate (U) and Graduate (G). The program allows users to input a student's name,
roll number, and type ('U' for Undergraduate or 'G' for Graduate). Depending on the type,
the program calculates and displays the total grade for the student.

Classes and Virtual Functions: Student (Base Class)

Virtual Functions
virtual void inputGrades(): Handles grade input.
virtual void calculateGrade(): Calculates and displays the total grade.

UndergraduateStudent (Derived Class):


Inherits from Student.
Overrides virtual functions for grade input and grade calculation for Undergraduate
students.

GraduateStudent (Derived Class):


Inherits from Student.
Overrides virtual functions for grade input and grade calculation for Graduate students.
Input Format
The first line of input consists of a string, representing the student's name.
The second line of input consists of a string, representing the student's roll number.
The third line of input consists of a character 'U' for Undergraduate student or 'G' for
Graduate student.
If the student is an Undergraduate student, the next two lines contain two integers
representing the midterm and final grades.
If the student is a Graduate student, the next two lines contain two integers representing the
research and presentation grades.
Output Format
The output displays the following information:

The first line of output should display "Name: " followed by the student's name.
The second line of output should display "Roll Number: " followed by the student's roll
number.
The third line of output should display "Total Grade: " followed by the calculated average
grade.

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ Length of name ≤ 20

studentType ∈ {'U', 'G'}


1 ≤ Length of rollNumber ≤ 10

0 ≤ grades ≤ 100
Sample Input Sample Output
John
12345
U
80
90
Name: John
Roll Number: 12345
Total Grade: 85
Sample Input Sample Output
Alice
67890
G
85
92
Name: Alice
Roll Number: 67890
Total Grade: 88
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

Sharon is working on a population growth analysis program. She is studying how populations
change over time.
She wants to write a program that calculates the growth rate of a population based on its
initial and final sizes.

Help Sharon write a program that includes a base class Popul and a derived class Birth.
Popul has a virtual function calcRate() to initialize the initial and final sizes. Class Birth
inherits from Popul, overriding calcRate() to calculate the growth rate based on births.

Note: Growth Rate = (1000 * (final polulation - initial population) / initial population)
Input Format
The first line of input consists of an integer N, representing the initial population.
The second line consists of an integer P, representing the final population.
Output Format
The output prints a double value, representing the population growth rate, rounded off to
two decimal places.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
10 ≤ N ≤ 107
10 ≤ P ≤ 107
Sample Input Sample Output
100
1000
9000.00
Sample Input Sample Output
456
768
684.21
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1Hidden Test CaseInputOutput
2
50.75
40.60
Weightage - 10InputOutput
1
3 75.00
225.00
Weightage - 10InputOutput
1
10000 49.99
499900.00
Weightage - 15InputOutput
2
2500.75
2000.60
Weightage - 15InputOutput
2
150000.00
120000.00
Weightage - 25InputOutput
1
1000 123.45
123450.00
Weightage - 25Sample InputSample Output
1
5 10.50
52.50
Sample InputSample Output
2
100.50
80.40
Sample InputSample Output
3
Invalid choice.
Solution
#include <iostream>
#include <iomanip>

using namespace std;

class ItemType {
public:
virtual double calculateAmount() {
return 0.0; // Default implementation, can be overridden in derived classes
}
};

class Wooden : public ItemType {


int noOfItems;
double cost;

public:
void get() {
cin >> noOfItems >> cost;
}

double calculateAmount() {
return noOfItems * cost;
}
};
class Electronics : public ItemType {
double cost;

public:
void get() {
cin >> cost;
}

double calculateAmount() {
double discount = cost * 0.20;
return (cost - discount);
}
};

int main() {
int choice;
cin >> choice;
if (choice == 1) {
Wooden w;
w.get();
cout << fixed << setprecision(2) << w.calculateAmount();
} else if (choice == 2) {
Electronics e;
e.get();
cout << fixed << setprecision(2) << e.calculateAmount();
} else {
cout << "Invalid choice." << endl;
}

return 0;
}
Q2Hidden Test CaseInputOutput
19 19 06 06
21 07 11 15
Weekday: 10h 47m
Weekend: 14h 8m
User slept more on the weekend.
Weightage - 20InputOutput
21 30 06 45
20 30 05 45
Weekday: 9h 15m
Weekend: 9h 15m
User slept the same amount on weekdays and weekend.
Weightage - 20InputOutput
17 25 06 06
11 50 11 05
Weekday: 12h 41m
Weekend: 23h 15m
User slept more on the weekend.
Weightage - 10InputOutput
20 15 08 55
22 24 09 50
Weekday: 12h 40m
Weekend: 11h 26m
User slept more on weekdays.
Weightage - 25InputOutput
23 59 09 50
22 00 06 58
Weekday: 9h 51m
Weekend: 8h 58m
User slept more on weekdays.
Weightage - 25Sample InputSample Output
22 50 07 32
20 54 10 19
Weekday: 8h 42m
Weekend: 13h 25m
User slept more on the weekend.
Sample InputSample Output
22 00 06 05
23 00 06 05
Weekday: 8h 5m
Weekend: 7h 5m
User slept more on weekdays.
Sample InputSample Output
22 00 06 00
21 00 05 00
Weekday: 8h 0m
Weekend: 8h 0m
User slept the same amount on weekdays and weekend.
Solution
#include <iostream>
using namespace std;

class SleepTracker {
public:
int bh;
int bm;
int wh;
int wm;

void inputTime() {
cin >> bh >> bm >> wh >> wm;
}
virtual void calcDuration() {}

int getTotalMinutes() {
return (wh - bh) * 60 + wm - bm;
}
};

class WeekdaySleep : public SleepTracker {


public:
void calcDuration() override {
int totalMins = getTotalMinutes();
if (totalMins < 0) {
totalMins += 24 * 60;
}
cout << "Weekday: " << totalMins / 60 << "h " << totalMins % 60 << "m" << endl;
}
};

class WeekendSleep : public SleepTracker {


public:
void calcDuration() override {
int totalMins = getTotalMinutes();
if (totalMins < 0) {
totalMins += 24 * 60;
}
cout << "Weekend: " << totalMins / 60 << "h " << totalMins % 60 << "m" << endl;
}
};

int main() {
WeekdaySleep wday;
WeekendSleep wend;

wday.inputTime();
wday.calcDuration();

wend.inputTime();
wend.calcDuration();

int weekdayDuration = wday.getTotalMinutes();


int weekendDuration = wend.getTotalMinutes();

if (weekdayDuration > weekendDuration) {


cout << "User slept more on weekdays." << endl;
}
else if (weekendDuration > weekdayDuration) {
cout << "User slept more on the weekend." << endl;
}
else {
cout << "User slept the same amount on weekdays and weekend." << endl;
}

return 0;
}
Q3Hidden Test CaseInputOutput
Bob
54321
U
75
60
Name: Bob
Roll Number: 54321
Total Grade: 67
Weightage - 10InputOutput
Eva
98765
G
92
88
Name: Eva
Roll Number: 98765
Total Grade: 90
Weightage - 10InputOutput
Mia
45678
G
78
84
Name: Mia
Roll Number: 45678
Total Grade: 81
Weightage - 15InputOutput
Sophia
11223
U
96
78
Name: Sophia
Roll Number: 11223
Total Grade: 87
Weightage - 15InputOutput
Isabella
55555
U
79
91
Name: Isabella
Roll Number: 55555
Total Grade: 85
Weightage - 25InputOutput
Liam
77777
G
68
75
Name: Liam
Roll Number: 77777
Total Grade: 71
Weightage - 25Sample InputSample Output
John
12345
U
80
90
Name: John
Roll Number: 12345
Total Grade: 85
Sample InputSample Output
Alice
67890
G
85
92
Name: Alice
Roll Number: 67890
Total Grade: 88
Solution
#include <iostream>
#include <string>

using namespace std;

class Student {
protected:
string name;
int rollNumber;

public:
Student(const string& name, int rollNumber) : name(name), rollNumber(rollNumber) {}

virtual void inputGrades() {


// Default implementation for inputGrades
}

virtual void calculateGrade() {


// Default implementation for calculateGrade
}

void displayDetails() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
}
};

class UndergraduateStudent : public Student {


private:
int midtermGrade;
int finalGrade;

public:
UndergraduateStudent(const string& name, int rollNumber) : Student(name, rollNumber)
{}

void inputGrades() {
cin >> midtermGrade;
cin >> finalGrade;
}

void calculateGrade() {
int totalGrade = (midtermGrade + finalGrade) / 2;
cout << "Total Grade: " << totalGrade << endl;
}
};

class GraduateStudent : public Student {


private:
int researchGrade;
int presentationGrade;

public:
GraduateStudent(const string& name, int rollNumber) : Student(name, rollNumber) {}

void inputGrades() {
cin >> researchGrade;
cin >> presentationGrade;
}

void calculateGrade() {
int totalGrade = (researchGrade + presentationGrade) / 2;
cout << "Total Grade: " << totalGrade << endl;
}
};

int main() {
string name;
int rollNumber;
char studentType;

cin >> name;


cin >> rollNumber;

cin >> studentType;

Student* student;

if (studentType == 'U') {
student = new UndergraduateStudent(name, rollNumber);
} else if (studentType == 'G') {
student = new GraduateStudent(name, rollNumber);
}

student->inputGrades();
student->displayDetails();
student->calculateGrade();

delete student;

return 0;
}
Q4Hidden Test CaseInputOutput
90
200
1222.22
Weightage - 10InputOutput
900
1000
111.11
Weightage - 10InputOutput
9000
10000
111.11
Weightage - 15InputOutput
5000
5678
135.60
Weightage - 15InputOutput
12000
100000
7333.33
Weightage - 25InputOutput
80000
100000
250.00
Weightage - 25Sample InputSample Output
100
1000
9000.00
Sample InputSample Output
456
768
684.21
Solution
#include <iostream>
#include <iomanip>

using namespace std;

class Popul {
public:
virtual double calcRate(int initP, int finalP) {
if (initP <= 0 || finalP <= initP) {
return -1.0;
}
}
};

class Birth : public Popul {


public:
double calcRate(int initP, int finalP) {
return 1000.0 * ((double)(finalP - initP) / initP);
}
};

int main() {
int initP, finalP;

cin >> initP;


cin >> finalP;

Birth growth;

double rate = growth.calcRate(initP, finalP);


cout << fixed << setprecision(2) << rate;

return 0;
}

VIT C_Structured and OOP_Lab 7_COD_Pure Virtual Functions


Test Summary
 No. of Sections: 1
 No. of Questions: 4
 Total Duration: 30 min
Section 1 - Coding
Section Summary
 No. of Questions: 4
 Duration: 30 min
Additional Instructions:
None
Q1.
Problem Statement

Rohith is designing a program that consists of a base class Expression with a pure virtual
function evaluate().

There are two derived classes PowerAB and PowerBA representing expressions of the form
ab and ba respectively, where a and b are real numbers. The program takes the values of a
and b as input and calculates and displays the power results for both types of expressions.

Note: Use the pow function from the math library to calculate the power value.
Input Format
The input consists of two space-separated double values a and b.
Output Format
The first line of output prints the value of ab as a double-value, rounded off to two decimal
places.
The second line prints the value of ba as a double-value, rounded off to two decimal places.

Refer to the sample output for formatting specifications.


Constraints
1.0 ≤ a, b ≤ 10.0
Sample Input Sample Output
4.5 2.0
20.25
22.63
Sample Input Sample Output
1.1 1.1
1.11
1.11
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

Design a program for a transport system operation. Create a base class Transport with a
pure virtual function named operate. Implement two derived classes, TransportA and
TransportB, which calculate and display the time taken to move between locations based on
the transport type.

The program takes input for the number of transport systems and their operations, then
outputs the time taken in seconds for each operation.

For TransportA: Time Taken = abs(start location - destination) * 2


For TransportB: Time Taken = abs(start location - destination) * 3
Input Format
The first line of input consists of an integer N, representing the number of transport
operations.
Each of the next N lines consists of three space-separated values:
1. A character - Transport type ('P/p' for TransportA or 'F/f' for TransportB)
2. An integer - Starting location
3. An integer - Destination
Output Format
For each transport operation, the output prints the time taken in seconds in the following
format:
"Time taken: X seconds" where X is the time taken in seconds.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ N ≤ 10
0 ≤ Starting location and Destination ≤ 10
Sample Input Sample Output
2
P15
F 3 10
Time taken: 8 seconds
Time taken: 21 seconds
Sample Input Sample Output
1
p37
Time taken: 8 seconds
Sample Input Sample Output
3
F53
P28
f72
Time taken: 6 seconds
Time taken: 12 seconds
Time taken: 15 seconds
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

Write a program to calculate the total cost of a meal for a group of people.

The program has a base class, MenuItem, with an attribute price and a pure virtual function
calculatePrice().

Two derived classes, Appetizer and MainCourse, inherit from MenuItem. They implement
the pure virtual function to calculate the total cost based on the price of the item and the
number of persons.

For Example,
If there are 4 people in the group, and if the number of appetizer items is 3 and the number
of main course items is 4.
1. The appetizer prices are 44.25, 53.50, 75.99.
2. The main course prices are 48.99, 53.25, 86.75, 92.00.
The total cost is calculated by adding all the costs and multiplying the number of people.
1. For appetizers: (44.25 + 53.50 + 75.99) = 173.74
2. For main courses: (48.99 + 53.25 + 86.75 + 92.00) = 280.99
Total cost = (173.74 + 280.99) * 4 = 454.73 * 4 = 1818.92.
Input Format
The first line of input consists of an integer n, representing the number of persons dining.
The second line consists of two space-separated integers, N - the number of appetizer items
and M - the number of main course items.
The third line consists of N space-separated floating-point numbers, representing the prices
of the N appetizer items.
The fourth line consists of M space-separated floating-point numbers, representing the
prices of the M main course items.
Output Format
The output prints "Rs. X" where X is a float value, representing the the total cost of the
menu items for the specified number of persons, rounded off to two decimal places.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ n ≤ 20
1 ≤ N, M ≤ 20
1.0 ≤ price ≤ 1000.0
Sample Input Sample Output
1
11
72.50
81.99
Rs. 154.49
Sample Input Sample Output
4
34
44.25 53.50 75.99
48.99 53.25 86.75 92.00
Rs. 1818.92
Sample Input Sample Output
11
55
5.99 4.75 3.99 7.50 12.25
6.75 15.99 3.25 10.00 10.00
Rs. 885.17
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

Imagine you are creating a hotel room pricing system with a class Hotel featuring a pure
virtual function calculatePrice() to calculate prices based on nights and guests. Derived
classes SingleRoom and DoubleRoom implement this function.

Base cost calculation:


1. For Single room - Rs. 100 per night
2. For Double room - Rs. 150 per night

Additional cost calculation:


1. If guests stay for more than 5 nights, they avail a 10% discount.
2. If guests stay for 5 or fewer nights, add Rs. 15 service charge.

The program takes user input for nights and guests and then calculates and displays costs for
both room types.
Input Format
The first line of input consists of an integer n, representing the number of nights the guests
will use the room.
The second line consists of an integer p, representing the number of guests.
Output Format
The first line of output prints "Single Room Cost: " followed by an integer representing the
cost for the single room.
The second line prints "Double Room Cost: " followed by an integer representing the cost for
the double room.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ n ≤ 10
1 ≤ p ≤ 20
Sample Input Sample Output
6
3
Single Room Cost: 540
Double Room Cost: 810
Sample Input Sample Output
3
7
Single Room Cost: 315
Double Room Cost: 465
Sample Input Sample Output
5
12
Single Room Cost: 515
Double Room Cost: 765
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1Hidden Test CaseInputOutput
2.5 3.0
15.62
15.59
Weightage - 10InputOutput
1.0 10.0
1.00
10.00
Weightage - 10InputOutput
4.0 4.0
256.00
256.00
Weightage - 15InputOutput
3.14 2.71
22.22
22.88
Weightage - 15InputOutput
10.0 2.5
316.23
9536.74
Weightage - 25InputOutput
10.0 10.0
10000000000.00
10000000000.00
Weightage - 25Sample InputSample Output
4.5 2.0
20.25
22.63
Sample InputSample Output
1.1 1.1
1.11
1.11
Solution
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

class Expression {
public:
virtual double evaluate() = 0;
};

class PowerAB : public Expression {


double a, b;
public:
PowerAB(double x, double y){
a = x;
b = y;
}
double evaluate() {
return pow(a, b);
}
};

class PowerBA : public Expression {


double a, b;
public:
PowerBA(double x, double y){
a = x;
b = y;
}
double evaluate() {
return pow(b, a);
}
};

int main() {
double a, b;
cin >> a >> b;

PowerAB exprAB(a, b);


PowerBA exprBA(a, b);
cout << fixed << setprecision(2) << exprAB.evaluate() << endl << exprBA.evaluate() <<
endl;
return 0;
}
Q2Hidden Test CaseInputOutput
2
F18
P53
Time taken: 21 seconds
Time taken: 4 seconds
Weightage - 10InputOutput
3
F 10 1
P 3 10
F75
Time taken: 27 seconds
Time taken: 14 seconds
Time taken: 6 seconds
Weightage - 10InputOutput
1
P74
Time taken: 6 seconds
Weightage - 15InputOutput
4
P 1 10
F32
P47
F59
Time taken: 18 seconds
Time taken: 3 seconds
Time taken: 6 seconds
Time taken: 12 seconds
Weightage - 15InputOutput
3
P28
F93
P64
Time taken: 12 seconds
Time taken: 18 seconds
Time taken: 4 seconds
Weightage - 25InputOutput
1
F73
Time taken: 12 seconds
Weightage - 25Sample InputSample Output
2
P15
F 3 10
Time taken: 8 seconds
Time taken: 21 seconds
Sample InputSample Output
1
p37
Time taken: 8 seconds
Sample InputSample Output
3
F53
P28
f72
Time taken: 6 seconds
Time taken: 12 seconds
Time taken: 15 seconds
Solution
#include <iostream>
using namespace std;

class Transport {
public:
virtual void operate(int start, int dest) = 0;
};

class TransportA : public Transport {


public:
void operate(int start, int dest) override {
int time = abs(start - dest) * 2;
cout << "Time taken: " << time << " seconds" << endl;
}
};

class TransportB : public Transport {


public:
void operate(int start, int dest) override {
int time = abs(start - dest) * 3;
cout << "Time taken: " << time << " seconds" << endl;
}
};

int main() {
int numTransports;
cin >> numTransports;

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


char transportType;
int start, dest;
cin >> transportType >> start >> dest;

if (transportType == 'P' || transportType == 'p') {


TransportA transportA;
transportA.operate(start, dest);
} else if (transportType == 'F' || transportType == 'f') {
TransportB transportB;
transportB.operate(start, dest);
}
}

return 0;
}
Q3Hidden Test CaseInputOutput
4
11
6.99
8.50
Rs. 61.96
Weightage - 10InputOutput
11
43
6.99 8.50 4.75 9.99
14.50 10.00 10.00
Rs. 712.03
Weightage - 20InputOutput
7
22
3.00 5.00
4.25 10.55
Rs. 159.60
Weightage - 20InputOutput
30
23
25.99 19.50
7.99 13.25 16.50
Rs. 2496.90
Weightage - 25InputOutput
15
55
4.99 6.25 8.50 3.75 9.99
14.25 7.99 5.50 12.75 10.00
Rs. 1259.55
Weightage - 25Sample InputSample Output
1
11
72.50
81.99
Rs. 154.49
Sample InputSample Output
4
34
44.25 53.50 75.99
48.99 53.25 86.75 92.00
Rs. 1818.92
Sample InputSample Output
11
55
5.99 4.75 3.99 7.50 12.25
6.75 15.99 3.25 10.00 10.00
Rs. 885.17
Solution
#include <iostream>
#include <iomanip>

using namespace std;

class MenuItem {
public:
float price;
MenuItem(float itemPrice) {
price = itemPrice;
}
virtual float calculatePrice(int numPersons) = 0;
};

class Appetizer : public MenuItem {


public:
Appetizer(float itemPrice) : MenuItem(itemPrice) {}

float calculatePrice(int numPersons) override {


return price * numPersons;
}
};

class MainCourse : public MenuItem {


public:
MainCourse(float itemPrice) : MenuItem(itemPrice) {}

float calculatePrice(int numPersons) override {


return price * numPersons;
}
};
int main() {
int numPersons;
cin >> numPersons;
int numAppetizers, numMainCourses;
cin >> numAppetizers >> numMainCourses;
float totalCost = 0.0;
for (int i = 0; i < numAppetizers; i++) {
float price;
cin >> price;
Appetizer appetizer(price);
totalCost += appetizer.calculatePrice(numPersons);
}
for (int i = 0; i < numMainCourses; i++) {
float price;
cin >> price;
MainCourse mainCourse(price);
totalCost += mainCourse.calculatePrice(numPersons);
}
cout << fixed << setprecision(2) << "Rs. " << totalCost;
return 0;
}
Q4Hidden Test CaseInputOutput
5
1
Single Room Cost: 515
Double Room Cost: 765
Weightage - 10InputOutput
7
4
Single Room Cost: 630
Double Room Cost: 945
Weightage - 10InputOutput
6
8
Single Room Cost: 540
Double Room Cost: 810
Weightage - 15InputOutput
8
3
Single Room Cost: 720
Double Room Cost: 1080
Weightage - 15InputOutput
4
20
Single Room Cost: 415
Double Room Cost: 615
Weightage - 25InputOutput
10
20
Single Room Cost: 900
Double Room Cost: 1350
Weightage - 25Sample InputSample Output
6
3
Single Room Cost: 540
Double Room Cost: 810
Sample InputSample Output
3
7
Single Room Cost: 315
Double Room Cost: 465
Sample InputSample Output
5
12
Single Room Cost: 515
Double Room Cost: 765
Solution
#include <iostream>
using namespace std;

class Hotel {
public:
virtual int calculatePrice(int nights, int people) = 0;
};

// Derived class for Single Room


class SingleRoom : public Hotel {
public:
int calculatePrice(int nights, int people) override {
int cost = nights * 100;

if (nights > 5) {
cost = cost - (cost * 0.1);
}
else {
cost = cost + 15;
}

return cost;
}
};

class DoubleRoom : public Hotel {


public:
int calculatePrice(int nights, int people) override {
int cost = nights * 150;

if (nights > 5) {
cost = cost - (cost * 0.1);
}
else {
cost = cost + 15;
}

return cost;
}
};

int main() {
SingleRoom singleRoom;
DoubleRoom doubleRoom;

int nights, people;


cin >> nights;
cin >> people;

int singleRoomCost = singleRoom.calculatePrice(nights, people);


int doubleRoomCost = doubleRoom.calculatePrice(nights, people);

cout << "Single Room Cost: " << singleRoomCost << endl;
cout << "Double Room Cost: " << doubleRoomCost << endl;

return 0;
}

VIT C_Structured and OOP_Lab 7_COD_Abstract Classes


Test Summary
 No. of Sections: 1
 No. of Questions: 4
 Total Duration: 30 min
Section 1 - Coding
Section Summary
 No. of Questions: 4
 Duration: 30 min
Additional Instructions:
None
Q1.
Problem Statement:
Write a Program to calculate the current bill.
Create a class currentBill with a virtual method double amount().
Create a Fan
Create a class Fan that extends currentBill with watts and hours as its public attributes and
overrides the virtual function.
Create a class Light that extends currentBill with watts and hours as its public attributes and
overrides the virtual function.
Create a class TV that extends currentBill with watts and hours as its public attributes and
overrides the virtual function.

In the main method, prompt the user to enter the power rate of the appliance and the total
hours used then create the necessary objects and call the methods.
Input Format
The first line consists of the power rating of the fan and the total hours used separated by
space.
The second line consists of the power rating of Light and the total hours used separated by
space.
The third line consists of the power rating of the TV and the total hours used separated by
space.
Output Format
The output prints the bill amount.

Refer to the sample input and output for formatting specifications.


Sample Input Sample Output
40 123
55 200
33 400
43.68
Sample Input Sample Output
60 300
54 360
30 720
88.56
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement:
Create a base class named operationsBase with the following four virtual functions
void addition()
void subtraction()
void multiplication()
void division()
Create a derived class named operationsDerived that extends operationsBase with a and b
as its private attributes and override the virtual functions.
Input Format
The input consists of two integers.
Output Format
The output prints the results of addition, subtraction, multiplication, and division separated
by a space.
Sample Input Sample Output
20 10
30 10 200 2
Sample Input Sample Output
5248 284
5532 4964 1490432 18
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement:
Alphabetics Game:
You have to enter four letters for each uppercase letter you will get 10 marks and for each
lowercase letter, you will get -5 marks.
Write a program to calculate the total score.
Create a base class with a virtual method void game(). Define this method in the Derived
class and calculate the total score.
Input Format
Input consists of four characters separated by space.
Output Format
The output prints the total score.
Sample Input Sample Output
AFKR
Score : 40
Sample Input Sample Output
AbDf
Score : 10
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement:
Create a base class ItemType with one virtual function
double calculateAmount()

Create a class wooden that extends ItemType with a number of items and cost as its private
attributes. Obtain the data members and override the virtual function.
amount = number of items*cost
Create a class electronics that extend ItemType with cost as its private attribute. Obtain the
data member and override the virtual function.
amount = 80% of the amount (20% discount)

In the main method, obtain a choice


If the choice is 1, create an object for the wooden class and call the method.
If the choice is 2, create an object for the electronics class and call the method.
Input Format
The first line of the input consists of the choice.
If the choice is 1, enter the number of items and cost.
If the choice is 2, enter the cost.
Output Format
The output prints the final amount.
Round off the output to two decimal places.
Sample Input Sample Output
1
5 840
4200.00
Sample Input Sample Output
2
1800
1440.00
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1Hidden Test CaseInputOutput
1500 8
1400 9
40 12
37.62
Weightage - 25InputOutput
700 120
500 300
100 700
456
Weightage - 25InputOutput
10 150
20 200
15 300
15
Weightage - 25InputOutput
23
27
28
0.054
Weightage - 25Sample InputSample Output
40 123
55 200
33 400
43.68
Sample InputSample Output
60 300
54 360
30 720
88.56
Solution
#include <iostream>

using namespace std;


class currentBill{
public:

virtual double amount()=0;


};

class Fan: public currentBill{


public:
int watts,hrs;
double amount(){
double t=watts*hrs;
double a= (t/1000)*1.5;
return a;
}
};

class Light: public currentBill{


public:
int watts,hrs;
double amount(){
double t=watts*hrs;
double a= (t/1000)*1.5;
return a;
}
};
class TV: public currentBill{
public:
int watts,hrs;
double amount(){
double t=watts*hrs;
double a= (t/1000)*1.5;
return a;
}
};
int main()
{
Fan f;
cin>>f.watts>>f.hrs;
Light l;
cin>>l.watts>>l.hrs;
TV t;
cin>>t.watts>>t.hrs;
cout<<f.amount()+l.amount()+t.amount();
return 0;
}
Q2Hidden Test CaseInputOutput
520 25
545 495 13000 20
Weightage - 20InputOutput
5248 284
5532 4964 1490432 18
Weightage - 20InputOutput
8888 88
8976 8800 782144 101
Weightage - 20InputOutput
4444 20
4464 4424 88880 222
Weightage - 20InputOutput
100 20
120 80 2000 5
Weightage - 20Sample InputSample Output
20 10
30 10 200 2
Sample InputSample Output
5248 284
5532 4964 1490432 18
Solution
#include<bits/stdc++.h>
using namespace std;

class operationsBase
{
public:
virtual void addition() = 0;
virtual void subtraction() = 0;
virtual void multiplication() = 0;
virtual void division() = 0;
};
class operationsDerived : public operationsBase
{
int a,b;
public:
int get()
{
cin>>a>>b;
}
void addition()
{
cout<<a+b<<" ";
}
void subtraction()
{
cout<<a-b<<" ";
}
void multiplication()
{
cout<<a*b<<" ";
}
void division()
{
cout<<a/b<<" ";
}
};

int main()
{
operationsDerived od;
od.get();
od.addition();
od.subtraction();
od.multiplication();
od.division();
return 0;
}
Q3Hidden Test CaseInputOutput
AFKR
Score : 40
Weightage - 20InputOutput
GHkl
Score : 10
Weightage - 20InputOutput
QnUI
Score : 25
Weightage - 20InputOutput
phdm
Score : -20
Weightage - 20InputOutput
FbGH
Score : 25
Weightage - 20Sample InputSample Output
AFKR
Score : 40
Sample InputSample Output
AbDf
Score : 10
Solution
#include <iostream>

using namespace std;


class Base{
public:
virtual void game()=0;
};
class Derived: public Base{
public:
char a,b,c,d;
int s=0;
void game() override{
if(a>='A'&&a<='Z'){
s=s+10;
}
else{
s=s-5;
}
if(b>='A'&&b<='Z'){
s=s+10;
}
else{
s=s-5;
}
if(c>='A'&&c<='Z'){
s=s+10;
}
else{
s=s-5;
}
if(d>='A'&&d<='Z'){
s=s+10;
}
else{
s=s-5;
}
cout<<"Score : "<<s;
}
};

int main()
{
Derived dd;
cin>>dd.a>>dd.b>>dd.c>>dd.d;
dd.game();

return 0;
}
Q4Hidden Test CaseInputOutput
1
8 6520
52160.00
Weightage - 20InputOutput
2
15236
12188.80
Weightage - 20InputOutput
1
15 5000
75000.00
Weightage - 20InputOutput
2
85235
68188.00
Weightage - 20InputOutput
1
10 200
2000.00
Weightage - 20Sample InputSample Output
1
5 840
4200.00
Sample InputSample Output
2
1800
1440.00
Solution
#include<bits/stdc++.h>
using namespace std;

class ItemType
{
public:
virtual double calculateAmount() = 0;
};

class wooden: public ItemType


{
int noOfItems;
double cost;
public:
int get()
{
cin>>noOfItems>>cost;
}
double calculateAmount()
{
return noOfItems*cost;
}
};

class electronics: public ItemType


{
double cost;
public:
int get()
{
cin>>cost;
}
double calculateAmount()
{
double discount = cost * 0.20;
return (cost-discount);
}

};

int main()
{
int choice;
cin>>choice;
if(choice ==1)
{
wooden w;
w.get();
cout<<fixed<<setprecision(2)<<w.calculateAmount();
}
if(choice ==2)
{
electronics e;
e.get();
cout<<fixed<<setprecision(2)<<e.calculateAmount();
}

You might also like