Assessment 2 Module 5 C++

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Diploma in Software Assessment 2 Ksenia Vyazalova

Development

Diploma in Software Development CS105 Development Principles II


Assessment 2
Practical Test

Section 1
Question 1: Pointer to Objects

Code C++
#include <iostream>
using namespace std;

// Class to represent HealthActivity


class HealthActivity {
private:
string userName;
int steps;
double walkingRunningDistance;

public:
// Constructor
HealthActivity(string name, int stepsCount, double distance) {
userName = name;
steps = stepsCount;
walkingRunningDistance = distance;
}

// Setter functions
void setName(string name) {
userName = name;
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

void setSteps(int stepsCount) {


steps = stepsCount;
}

void setWalkingRunningDistance(double distance) {


walkingRunningDistance = distance;
}

// Getter functions
string getName() {
return userName;
}

int getSteps() {
return steps;
}

double getWalkingRunningDistance() {
return walkingRunningDistance;
}
};

// Function to set user input for HealthActivity objects


void setFunction(HealthActivity* activities[], int size) {
cout << "Enter the name, number of steps and walking + running distance:\n";
for (int i = 0; i < size; i++) {
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

string name;
int steps;
double distance;

cout << "User " << i + 1 << ": ";


cin >> name >> steps >> distance;

// Create HealthActivity object and assign it to the array of pointers


activities[i] = new HealthActivity(name, steps, distance);
}
}

// Function to display user data for HealthActivity objects


void getFunction(HealthActivity* activities[], int size) {
int totalSteps = 0;
double totalDistance = 0.0;

cout << "\nUser Data:\n";


for (int i = 0; i < size; i++) {
cout << "Name: " << activities[i]->getName() << endl;
cout << "Steps: " << activities[i]->getSteps() << " steps" << endl;
cout << "Walking + Running: " << activities[i]->getWalkingRunningDistance() << " Kms"
<< endl;
cout << endl;

totalSteps += activities[i]->getSteps();
totalDistance += activities[i]->getWalkingRunningDistance();
}
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

// Calculate average steps and average distance


int averageSteps = totalSteps / size;
double averageDistance = totalDistance / size;

cout << "Average steps of " << size << " users: " << averageSteps << " steps" << endl;
cout << "Average distance of walking + running for " << size << " users: " <<
averageDistance << " Kms" << endl;
}

int main() {
const int NUM_USERS = 5;
HealthActivity* activityArray[NUM_USERS]; // Array of pointers to HealthActivity objects

setFunction(activityArray, NUM_USERS);
getFunction(activityArray, NUM_USERS);

// Deallocate memory for HealthActivity objects


for (int i = 0; i < NUM_USERS; i++) {
delete activityArray[i];
}

return 0;
}

OUTPUT
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

EXPLANATION:
The code is designed to handle health activity data for users of the Health app on an iPhone 12
Pro Max. It creates a class called HealthActivity to represent the activities of each user. The
class has attributes like userName, steps, and walkingRunningDistance, which store the user's
name, number of steps, and distance walked or run.
The program starts by asking the user to input the name, number of steps, and walking + running
distance for each user. It prompts the user five times to input this data. The information entered
by the user is stored in an array of pointers to HealthActivity objects.
The setFunction function is responsible for taking user input and creating the HealthActivity
objects. It iterates over the array and prompts the user to enter the details for each user. It creates
a new HealthActivity object using the provided input and assigns it to the corresponding
position in the array.
The getFunction function displays the user data for each HealthActivity object in the array. It
iterates over the array, retrieves the user data using getter functions, and prints it on the screen.
Additionally, it calculates the total steps and total distance for all the users.
Finally, it calculates the average steps and average distance by dividing the total steps and total
distance by the number of users. It displays the average values on the screen along with
appropriate units.
The main function serves as the entry point of the program. It declares the array of pointers to
HealthActivity objects, calls the setFunction to populate the array with user input, and then
calls the getFunction to display the user data and average values. It also takes care of
deallocating the memory allocated for the HealthActivity objects to avoid memory leaks.
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

PART 2:

Question 3: Operator Overloading

Code C++:
#include <iostream>

using namespace std;

// Define a class for complex numbers


class Complex {
private:
int real; // Real part of the complex number
int imaginary; // Imaginary part of the complex number

public:
// Constructor to initialize the complex number
Complex(int r = 0, int i = 0) {
real = r;
imaginary = i;
}

// Overload the + operator for addition of complex numbers


Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imaginary = imaginary + obj.imaginary;
return res;
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

// Overload the - operator for subtraction of complex numbers


Complex operator-(Complex const &obj) {
Complex res;
res.real = real - obj.real;
res.imaginary = imaginary - obj.imaginary;
return res;
}

// Overload the * operator for multiplication of complex numbers


Complex operator*(Complex const &obj) {
Complex res;
res.real = (real * obj.real) - (imaginary * obj.imaginary);
res.imaginary = (real * obj.imaginary) + (imaginary * obj.real);
return res;
}

// Display the complex number


void display() {
cout << real << " + " << imaginary << "i" << endl;
}
};

int main() {
int real, imaginary;

// Get the values for the first complex number from the user
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

cout << "1st Complex number:" << endl;


cout << "Enter Real value: ";
cin >> real;
cout << "Enter imaginary value: ";
cin >> imaginary;

// Create the first complex number object using the values entered by the user
Complex c1(real, imaginary);

// Get the values for the second complex number from the user
cout << "\nEnter 2nd Complex number values:" << endl;
cout << "Enter Real value: ";
cin >> real;
cout << "Enter imaginary value: ";
cin >> imaginary;

// Create the second complex number object using the values entered by the user
Complex c2(real, imaginary);

int choice;
Complex result;

// Display the menu and perform operations based on user's choice


do {
cout << "\nChoose an operation from Menu:" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "3. Multiplication" << endl;
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

cout << "4. Exit" << endl;


cout << "\nPlease enter option: ";
cin >> choice;

switch (choice) {
case 1:
// Perform addition of the two complex numbers
result = c1 + c2;
cout << "\nC1: ";
c1.display();
cout << "C2: ";
c2.display();
cout << "C3: ";
result.display();
break;

case 2:
// Perform subtraction of the two complex numbers
result = c1 - c2;
cout << "\nC1: ";
c1.display();
cout << "C2: ";
c2.display();
cout << "C3: ";
result.display();
break;

case 3:
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

// Perform multiplication of the two complex numbers


result = c1 * c2;
cout << "\nC1: ";
c1.display();
cout << "C2: ";
c2.display();
cout << "C3: ";
result.display();
break;

case 4:
break;

default:
cout << "Invalid option. Please try again." << endl;
break;
}
} while (choice != 4);

return 0;
}

Explanation of the code:


1. The code begins with the inclusion of necessary libraries, including <iostream> for
input/output operations.
2. We define a class called Complex to represent complex numbers. This class has private
data members real and imaginary to store the real and imaginary parts of the complex
number, respectively.
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

3. Inside the Complex class, there is a constructor that initializes the complex number with
default values of 0 for both the real and imaginary parts. The constructor can also be used
to initialize the complex number with specific values.
4. The Complex class overloads three arithmetic operators: +, -, and *. These operators are
used to perform addition, subtraction, and multiplication operations on complex numbers.
5. The operator+ function overloads the + operator and performs addition of two complex
numbers. It creates a new Complex object and sets its real part as the sum of the real
parts of the two complex numbers, and sets its imaginary part as the sum of the imaginary
parts of the two complex numbers. The result is then returned.
6. Similarly, the operator- function overloads the - operator for subtraction of complex
numbers, and the operator* function overloads the * operator for multiplication of
complex numbers. Both of these functions follow a similar logic to perform the
respective operations.
7. The display function is used to display the complex number in the format "real +
imaginary i".
8. In the main function, the user is prompted to enter the real and imaginary parts of the
first complex number. These values are then used to create a Complex object called c1.
9. Similarly, the user is prompted to enter the real and imaginary parts of the second
complex number. These values are used to create another Complex object called c2.
10. Inside the do-while loop, the user is presented with a menu where they can choose the
operation to perform on the complex numbers: addition, subtraction, multiplication, or
exit.
11. Based on the user's choice, the corresponding operation is performed using the
overloaded operators, and the result is stored in the result variable.
12. The display function is then called on the c1, c2, and result objects to display the
complex numbers before and after the operation.
13. The loop continues until the user chooses to exit by entering 4.
14. Finally, the program ends with a return 0 statement.

OUTPUT
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

Question 2: Polymorphism
Code C++
#include <iostream>
#include <string>

// Base class representing a video game


class VideoGame {
protected:
std::string title;
double price;

public:
// Constructor to initialize the title and price of the game
VideoGame(const std::string& gameTitle, double gamePrice)
: title(gameTitle), price(gamePrice) {}
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

// Virtual function to display the game details


virtual void display() const {
std::cout << "Title: " << title << std::endl;
std::cout << "Price: " << price << std::endl;
}
};

// Derived class representing a computer game


class ComputerGame : public VideoGame {
private:
std::string osType;

public:
// Constructor to initialize the title, price, and OS type of the computer game
ComputerGame(const std::string& gameTitle, double gamePrice, const std::string&
gameOsType)
: VideoGame(gameTitle, gamePrice), osType(gameOsType) {}

// Override the display function to include the OS type


void display() const override {
std::cout << "***********************" << std::endl;
VideoGame::display();
std::cout << "OS Type: " << osType << std::endl;
}
};

// Derived class representing a console game


class ConsoleGame : public VideoGame {
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

private:
std::string consoleType;

public:
// Constructor to initialize the title, price, and console type of the console game
ConsoleGame(const std::string& gameTitle, double gamePrice, const std::string&
gameConsoleType)
: VideoGame(gameTitle, gamePrice), consoleType(gameConsoleType) {}

// Override the display function to include the console type


void display() const override {
std::cout << "***********************" << std::endl;
VideoGame::display();
std::cout << "Console Type: " << consoleType << std::endl;
}
};

int main() {
const int MAX_GAMES = 100;
VideoGame* videoGamesArray[MAX_GAMES];
int numGames = 0;
std::string choice;

// Prompt the user for video game data entry


std::cout << "Video Games Data Entry" << std::endl;
std::cout << "****************************" << std::endl;

do {
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

std::string title;
double price;
std::string gameType;

// Prompt the user for the type of game (computer or console)


std::cout << "Do you want to enter data for a Computer Game or a Console Game (o / c): ";
std::cin >> gameType;

if (gameType == "o") {
std::string osType;

// Prompt the user for computer game details


std::cout << "Please enter title of computer game: ";
std::cin.ignore();
std::getline(std::cin, title);

std::cout << "Please enter price: ";


std::cin >> price;

std::cout << "Please enter operating system type: ";


std::cin.ignore();
std::getline(std::cin, osType);

// Create a new ComputerGame object and store it in the array


videoGamesArray[numGames] = new ComputerGame(title, price, osType);
} else if (gameType == "c") {
std::string consoleType;
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

// Prompt the user for console game details


std::cout << "Please enter title of console game: ";
std::cin.ignore();
std::getline(std::cin, title);

std::cout << "Please enter price: ";


std::cin >> price;

std::cout << "Please enter console type: ";


std::cin.ignore();
std::getline(std::cin, consoleType);

// Create a new ConsoleGame object and store it in the array


videoGamesArray[numGames] = new ConsoleGame(title, price, consoleType);
}

numGames++;

// Prompt the user if they want to add another item


std::cout << "Do you want to add another item (y/n): ";
std::cin >> choice;
} while (choice == "y");

// Display the list of video games entered by the user


std::cout << std::endl << "Video Games List:" << std::endl;
std::cout << "***********************" << std::endl;

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


Diploma in Software Assessment 2 Ksenia Vyazalova
Development

videoGamesArray[i]->display();
}

// Clean up allocated memory


for (int i = 0; i < numGames; i++) {
delete videoGamesArray[i];
}

return 0;
}

Code explanation:
This program allows the user to enter data for video games, either computer games or console
games. It uses object-oriented programming principles with inheritance and polymorphism.
Here's a breakdown of the code:
 The VideoGame class is the base class representing a video game. It has member
variables title and price to store the game's title and price, respectively. It also has a
virtual function display() to display the game details.
 The ComputerGame class is derived from VideoGame and represents a computer game.
It adds an additional member variable osType to store the operating system type. It
overrides the display() function to include the OS type in the output.
 The ConsoleGame class is also derived from VideoGame and represents a console
game. It adds a member variable consoleType to store the console type. It overrides the
display() function to include the console type in the output.
 In the main() function, an array of VideoGame pointers videoGamesArray is declared
to store the entered video games. numGames keeps track of the number of games
entered.
 The user is prompted to enter data for a computer game or a console game using a do-
while loop. Inside the loop, the user is asked for the game type, and based on the choice,
the program prompts for the game details (title, price, and additional details specific to
computer or console game). The entered game is then dynamically allocated using new
and stored in the videoGamesArray.
 After exiting the loop, the program displays the list of entered video games by calling the
display() function for each game in the array.
Diploma in Software Assessment 2 Ksenia Vyazalova
Development

 Finally, memory allocated for the video games is cleaned up using delete to avoid
memory leaks.

Output (Question 2: Polymorphism)

You might also like