[go: up one dir, main page]

0% found this document useful (0 votes)
168 views68 pages

C++ Revision Questions - 2

The document contains solutions to questions about C++ concepts like variables, constants, object-oriented programming principles, functions, switch statements, conditional operators, recursion, and more. One solution defines a variable as a container that can change value during program execution, while a constant cannot change once initialized. It also explains the characteristics of object-oriented programming like encapsulation, abstraction, inheritance, and polymorphism. Another solution demonstrates using a switch statement to create a menu-driven calculator program. It accepts a choice from the user and performs the corresponding operation like addition, subtraction, etc. A third solution finds the largest of three numbers entered by the user using a max function and conditional operator.

Uploaded by

kijanavictor96
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)
168 views68 pages

C++ Revision Questions - 2

The document contains solutions to questions about C++ concepts like variables, constants, object-oriented programming principles, functions, switch statements, conditional operators, recursion, and more. One solution defines a variable as a container that can change value during program execution, while a constant cannot change once initialized. It also explains the characteristics of object-oriented programming like encapsulation, abstraction, inheritance, and polymorphism. Another solution demonstrates using a switch statement to create a menu-driven calculator program. It accepts a choice from the user and performs the corresponding operation like addition, subtraction, etc. A third solution finds the largest of three numbers entered by the user using a max function and conditional operator.

Uploaded by

kijanavictor96
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/ 68

C++ : THE COMPLETE REVISION GUIDE:

FROM BASICS TO ANDAVANCED:


Question 1:

Solution:
(a). A variable is a container that can store data of a certain type and can change its value during
the program execution. A constant is a container that can store data of a certain type but cannot
change its value once it is initialized. For example:
// declare a variable of type int and assign it a value of 10
int x = 10;
// declare a constant of type int and assign it a value of 20
const int y = 20;
// change the value of x to 15
x = 15;
// try to change the value of y to 25
y = 25; // this will cause a compile-time error

In C++, we use variables to store and manipulate data that may vary during the program
execution. We use constants to store and represent fixed values that are unlikely to change or that
we do not want to change

(b). Object oriented programming (OOP) is a programming paradigm that organizes data and
behavior into reusable units called objects. OOP has several characteristics that distinguish it
from other paradigms, such as:

 Encapsulation: This means that each object has its own internal state and methods that
operate on that state. The object hides the details of its implementation from the outside
world and only exposes a public interface that defines how the object can be used.

 Abstraction: This means that each object provides a simplified and generalized
representation of a concept or a problem domain. The object abstracts away the
unnecessary or irrelevant details and focuses on the essential features and behavior.
 Inheritance: This means that an object can inherit the properties and methods of another
object, called its parent or superclass. The object can then add or override some of the
inherited features to customize its own behavior. This allows for code reuse and
hierarchical organization of objects.

 Polymorphism: This means that an object can have different forms or behaviors
depending on the context. For example, an object can have different implementations of
the same method, called overloading, or an object can behave differently depending on its
type, called overriding. This allows for dynamic and flexible behavior of objects.

©. // C++ program to grade students based on their marks


#include <iostream>
using namespace std;

// A class to store the student's marks and grade


class Student {
public:
int marks; // the marks obtained by the student
string grade; // the grade assigned to the student
// A constructor to initialize the marks and grade
Student(int m) {
marks = m;
grade = "";
}

// A function to calculate and return the grade based on the marks


string getGrade() {
if (marks >= 70 && marks <= 100) {
grade = "First class honors";
}
else if (marks >= 60 && marks < 70) {
grade = "Second class honors";
}
else if (marks >= 50 && marks < 60) {
grade = "Second lower class honors";
}
else if (marks >= 40 && marks < 50) {
grade = "Pass";
}
else if (marks >= 0 && marks < 40) {
grade = "Fail";
}
else {
grade = "Invalid marks";
}
return grade;
}
};

// The main function


int main() {
// An array to store the marks of 5 students
int marks[5];
// A loop to take the input of the marks
cout << "Enter the marks of 5 students: " << endl;
for (int i = 0; i < 5; i++) {
cin >> marks[i];
}
// An array to store the objects of the Student class
Student students[5] = {Student(marks[0]), Student(marks[1]), Student(marks[2]),
Student(marks[3]), Student(marks[4])};
// A loop to display the output using the given format
cout << "\n# \tMarks \tGrade" << endl;
for (int i = 0; i < 5; i++) {
cout << i+1 << "\t" << students[i].marks << "\t" << students[i].getGrade() << endl;
}
return 0;
}

(d). With an example, explain how a C++ function is defined.

A C++ function is a block of code that performs a specific task and can be called from
other parts of the program. A C++ function has two parts: the declaration and the
definition. The declaration specifies the name, the return type, and the parameters of the
function. The definition provides the body of the function, which contains the statements
that execute when the function is called. For example:

// Function declaration
int add(int a, int b); // the function name is add, the return type is int, and the parameters are two
int values

// Function definition
int add(int a, int b) {
int result = a + b; // the body of the function, which calculates the sum of a and b and stores it in
result
return result; // the function returns the value of result
}

// Function call
int main() {
int x = 10;
int y = 5;
int z = add(x, y); // the function add is called with the arguments x and y, and the return value is
assigned to z
cout << "The sum is " << z << endl; // the output is "The sum is 15"
return 0;
}

(e). Write a C++ program which output even numbers and their squares in a
tabular format. The even numbers being calculated range from 0 to 200 inclusive.

// C++ program to output even numbers and their squares


#include <iostream>
using namespace std;

int main() {
// Declare variables
int number, square;
// Print the header of the table
cout << "No \tSquare" << endl;
// Loop from 0 to 200 with an increment of 2
for (number = 0; number <= 200; number += 2) {
// Calculate the square of the number
square = number * number;
// Print the number and its square in a tabular format
cout << number << "\t" << square << endl;
}
return 0;
}

Question 2:

Solution:

(a). The C++ program using switch decision statement to display a menu for users and execute
the selected operation is:

#include <iostream>
using namespace std;
int main()
{
int choice, num1, num2, result;
bool quit = false;
while (!quit) // repeat until the user chooses to quit
{
// display the menu
cout << "Choose an operation:\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "3. Divide\n";
cout << "4. Multiply\n";
cout << "5. Quit\n";
cout << "Enter your choice: ";
cin >> choice; // get the user's choice

// execute the selected operation


switch (choice)
{
case 1: // add
cout << "Enter two numbers: ";
cin >> num1 >> num2; // get the numbers
result = num1 + num2; // calculate the sum
cout << "The sum is " << result << endl; // display the output
break;
case 2: // subtract
cout << "Enter two numbers: ";
cin >> num1 >> num2; // get the numbers
result = num1 - num2; // calculate the difference
cout << "The difference is " << result << endl; // display the output
break;
case 3: // divide
cout << "Enter two numbers: ";
cin >> num1 >> num2; // get the numbers
if (num2 == 0) // check for zero division
{
cout << "Invalid input. Cannot divide by zero.\n";
}
else
{
result = num1 / num2; // calculate the quotient
cout << "The quotient is " << result << endl; // display the output
}
break;
case 4: // multiply
cout << "Enter two numbers: ";
cin >> num1 >> num2; // get the numbers
result = num1 * num2; // calculate the product
cout << "The product is " << result << endl; // display the output
break;
case 5: // quit
quit = true; // set the quit flag to true
cout << "Thank you for using the program. Goodbye.\n";
break;
default: // invalid choice
cout << "Invalid choice. Please try again.\n";
break;
}
}
return 0;
}

b) The object-oriented program in C++ that accepts three numbers and prints out the largest one
using a conditional operator and a user-defined function is:

#include <iostream>
using namespace std;

// a user-defined function that accepts three numbers and returns the largest one
int max(int a, int b, int c)
{
// use the conditional operator to compare the numbers and return the largest one
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}

int main()
{
int num1, num2, num3, largest;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3; // get the numbers
largest = max(num1, num2, num3); // call the max function and store the result
cout << "The largest number is " << largest << endl; // display the output
return 0;
}

c) A recursive function is a function that calls itself in its definition, with each call representing
a specific instance or version of that function. A recursive function usually has two parts: a base
case and a recursive case. The base case is the simplest or smallest version of the problem that
can be solved directly, without any further recursion. The recursive case is the general or larger
version of the problem that can be reduced to a smaller or simpler version by calling the same
function again, with different arguments. A recursive function must have a way to terminate or
end the recursion, otherwise it will result in an infinite loop or a stack overflow.
The C++ recursive function that calculates the factorial of an integer n entered from the keyboard
is:
#include <iostream>
using namespace std;

// a recursive function that calculates the factorial of an integer n


int factorial(int n)
{
// base case: if n is 0 or 1, return 1
if (n == 0 || n == 1)
{
return 1;
}
// recursive case: if n is greater than 1, return n times the factorial of n-1
else
{
return n * factorial(n - 1);
}
}

int main()
{
int n, result;
cout << "Enter a positive integer: ";
cin >> n; // get the number
result = factorial(n); // call the factorial function and store the result
cout << "The factorial of " << n << " is " << result << endl; // display the output
return 0;
}

Question 3:
Solution:
a) The C++ standard library provides numerous built-in functions that your program can call.
Some of these functions are:

 cout: This function is used to print or display output to the standard output device, usually
the screen. It is defined in the <iostream> header file and belongs to the std namespace.
 cin: This function is used to read or accept input from the standard input device, usually
the keyboard. It is also defined in the <iostream> header file and belongs to
the std namespace.
 sqrt: This function is used to calculate the square root of a given number. It is defined in
the <cmath> header file and returns a floating-point value.
 strlen: This function is used to find the length of a string, i.e., the number of characters in
the string. It is defined in the <cstring> header file and returns an integer value.

b) The program that reads two values from the keyboard and calculates their sum using two
functions is:
#include <iostream>
using namespace std;

// a user-defined function that accepts two numbers and returns their sum
int getsum(int a, int b)
{
return a + b; // calculate and return the sum
}

int main()
{
int num1, num2, sum;
cout << "Enter two numbers: ";
cin >> num1 >> num2; // get the numbers
sum = getsum(num1, num2); // call the getsum function and store the result
cout << "The sum is " << sum << endl; // display the output
return 0;
}

c) C++ is a high-level language with strong support of object-oriented programming. Some of


the OOP concepts are:

 Encapsulation: This is the concept of wrapping or combining data and functions into a
single unit called an object. This helps to protect the data from being accessed or
modified by unauthorized or external code. It also provides a clear interface for the
object’s functionality and reduces complexity and dependencies.
 Inheritance: This is the concept of creating new classes from existing classes by
inheriting or reusing their attributes and methods. This helps to avoid code duplication
and achieve code reusability. It also enables hierarchical relationships and polymorphism
among classes.
 Polymorphism: This is the concept of having multiple forms or behaviors of the same
entity. This can be achieved by using inheritance and virtual functions. Polymorphism
allows the same function name or operator to perform different actions depending on the
type or class of the object. This helps to achieve dynamic binding and flexibility in code.

d) An infinite loop is a loop that never ends or terminates. It can be caused by a logical error, a
missing or incorrect condition, or a deliberate design choice. An infinite loop can result in an
unresponsive or crashing program, or a high CPU or memory usage.
An example of an infinite loop in C++ is:
#include <iostream>
using namespace std;

int main()
{
int i = 0; // initialize a variable
while (true) // a condition that is always true
{
cout << i << endl; // print the variable
i++; // increment the variable
}
return 0; // this statement is never reached
}

Question 4:

Solution:
a) The program that displays a table that shows Earth’s pounds and their equivalent moon weight
is:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
double earth_pounds, moon_weight;
cout << "Earth's pounds and their equivalent moon weight\n";
cout << "-----------------------------------------------\n";
cout << setw(10) << "Earth" << setw(10) << "Moon\n"; // set the column width and print the
headers
for (earth_pounds = 1; earth_pounds <= 100; earth_pounds++) // loop from 1 to 100 pounds
{
moon_weight = earth_pounds * 0.17; // calculate the moon weight
cout << setw(10) << earth_pounds << setw(10) << moon_weight << endl; // print the values
if (earth_pounds % 25 == 0) // output a new line every 25 pounds
{
cout << endl;
}
}
return 0;
}

b) The program that creates an array of ten elements and assigns each element value, computes
the average, minimum, and maximum values, and displays them is:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int array[10], sum = 0, min, max;
double average;
srand(time(0)); // seed the random number generator
cout << "The array elements are:\n";
for (int i = 0; i < 10; i++) // loop through the array
{
array[i] = rand() % 100 + 1; // assign a random value between 1 and 100
cout << array[i] << " "; // print the value
sum += array[i]; // add the value to the sum
}
cout << endl;
average = sum / 10.0; // calculate the average
min = max = array[0]; // initialize the min and max to the first element
for (int i = 1; i < 10; i++) // loop through the array again
{
if (array[i] < min) // if the element is smaller than the min
{
min = array[i]; // update the min
}
if (array[i] > max) // if the element is larger than the max
{
max = array[i]; // update the max
}
}
cout << "The average is " << average << endl; // display the average
cout << "The minimum is " << min << endl; // display the minimum
cout << "The maximum is " << max << endl; // display the maximum
return 0;
}

c) Given the flexibility inherent in all of C++’s loops, what criteria should one use when
selecting a loop? i.e., how does one choose the right loop for a specific job?

 One possible criterion is to consider the number of iterations or repetitions that the loop
needs to perform. If the number is fixed or known in advance, then a for loop might be a
good choice, as it allows specifying the initial, final, and increment values of a loop
control variable. If the number is variable or unknown in advance, then a while or do-
while loop might be more suitable, as they allow specifying a condition that determines
when the loop ends.
 Another possible criterion is to consider the location or placement of the condition that
controls the loop. If the condition needs to be checked before entering the loop, then
a while loop might be a good choice, as it evaluates the condition at the beginning of each
iteration. If the condition needs to be checked after executing the loop body, then a do-
while loop might be more appropriate, as it evaluates the condition at the end of each
iteration. A for loop can also be used in either case, as it allows placing the condition
anywhere in the loop header.

d) Explain the following programming terminologies:

 Identifiers: Identifiers are the names given to various elements in a program, such as
variables, constants, functions, classes, etc. Identifiers help to identify and refer to these
elements in the code. Identifiers must follow certain rules and conventions, such as
starting with a letter or underscore, not containing spaces or special symbols, not being a
reserved keyword, etc.
 Data structure: A data structure is a way of organizing and storing data in a program,
such that it can be accessed and manipulated efficiently and effectively. Data structures
can be classified into two types: built-in and user-defined. Built-in data structures are
those that are provided by the programming language, such as arrays, strings, etc. User-
defined data structures are those that are created by the programmer, such as structures,
classes, etc.
 Constant: A constant is a value or expression that does not change during the execution
of a program. Constants can be used to represent fixed or known values, such as
mathematical constants, physical constants, etc. Constants can be declared using
the const keyword, which prevents them from being modified or reassigned.

Question 5:
Solution:
b) Operator overloading and function overloading are two features of C++ that allow defining
multiple meanings or behaviors for the same symbol or name. The difference between them is:

 Operator overloading is the process of redefining the meaning or action of an existing


operator, such as +, -, *, etc., for a user-defined data type, such as a class or a structure.
For example, one can overload the + operator to perform the addition of two objects of a
class, instead of the default addition of two numbers.
 Function overloading is the process of defining multiple functions with the same name,
but different parameters or arguments. The compiler determines which function to call
based on the number, type, or order of the arguments passed to the function. For example,
one can overload a function named sum to calculate the sum of two integers, two
doubles, or an array of numbers.

c) To declare and initialize an array called AVERAGES to contain the following averages, one
can use the following code:
#include <iostream>
using namespace std;

int main()
{
// declare and initialize the array with the given values
double AVERAGES[5][4] = {
{36.20, 30.00, 67.20, 100.00},
{53.65, 93.50, 45.60, 21.90},
{20.70, 45.30, 67.30, 78.36},
{92.45, 35.90, 67.45, 90.45},
{45.60, 67.80, 34.50, 56.70}
};

// display the array elements


cout << "The array elements are:\n";
for (int i = 0; i < 5; i++) // loop through the rows
{
for (int j = 0; j < 4; j++) // loop through the columns
{
cout << AVERAGES[i][j] << " "; // print the element
}
cout << endl; // print a new line after each row
}
return 0;
}

d) A program that calculates the volume of a cylinder using a function basearea() and its return
value in the main() to calculate the volume is:
#include <iostream>
#include <cmath>
#define PI 3.14159 // define a constant for pi

// a user-defined function that calculates the base area of a cylinder given its radius
double basearea(double radius)
{
return PI * pow(radius, 2); // return the area using the formula pi * r^2
}

int main()
{
double radius, height, volume, area;
std::cout << "Enter the radius and height of the cylinder: ";
std::cin >> radius >> height; // get the radius and height
area = basearea(radius); // call the basearea function and store the result
volume = area * height; // calculate the volume using the formula area * height
std::cout << "The volume of the cylinder is " << volume << std::endl; // display the volume
return 0;
}
Question 6:

Solution:
#include <iostream>
using namespace std;

class Date
{
private:
int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
string names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int day;
int month;
int year;

public:
Date(int d,int m,int y): day(d), month(m), year(y) {}

bool isLeapYear() {
if(year % 4 != 0) {
return false;
} else if(year % 100 != 0) {
return true;
} else if(year % 400 != 0) {
return false;
} else {
return true;
}
}
};

int main() {
// Example usage: Create a date and check if its year is a leap year
Date date(15, 2 ,2004);
cout << (date.isLeapYear() ? "Leap Year" : "Not a Leap Year") << endl;

return 0;
}

(b). Write the definition of set functions such that their calls can be cascaded.

To write the definition of set functions that can be cascaded, you need to make sure that each
function returns a reference to the Date object itself. This way, you can chain multiple calls to
the set functions and modify the date attributes in one line.
For example, you can write the set functions as follows:

// Set the day value and return a reference to the Date object
Date& Date::setDay(int d) {
// Check if the day is valid for the given month and year
if(d > 0 && d <= days[month-1]) {
// If the month is February and the year is a leap year, add one more day
if(month == 2 && isLeapYear()) {
d++;
}
// Assign the day value
day = d;
} else {
// If the day is invalid, print an error message
cout << "Invalid day value: " << d << endl;
}
// Return a reference to the Date object
return *this;
}

// Set the month value and return a reference to the Date object
Date& Date::setMonth(int m) {
// Check if the month is valid
if(m > 0 && m <= 12) {
// Assign the month value
month = m;
} else {
// If the month is invalid, print an error message
cout << "Invalid month value: " << m << endl;
}
// Return a reference to the Date object
return *this;
}

// Set the year value and return a reference to the Date object
Date& Date::setYear(int y) {
// Check if the year is valid
if(y >= 2000 && y <= 2100) {
// Assign the year value
year = y;
} else {
// If the year is invalid, print an error message
cout << "Invalid year value: " << y << endl;
}
// Return a reference to the Date object
return *this;
}

With these set functions, you can cascade the calls like this:
// Create a date object
Date date(15, 2, 2004);

// Cascade the set functions to change the date to 29 Feb 2020


date.setDay(29).setMonth(2).setYear(2020);

C. Write definition of get function for each of the instance variable.


To write the definition of get function for each of the instance variable, you need to make sure
that each function returns the value of the corresponding private member of the Date class. You
can also use the const keyword to indicate that the functions do not modify the state of the
object.
For example, you can write the get functions as follows:
// Get the day value and return it
int Date::getDay() const {
// Return the day value
return day;
}

// Get the month value and return it


int Date::getMonth() const {
// Return the month value
return month;
}

// Get the year value and return it


int Date::getYear() const {
// Return the year value
return year;
}

With these get functions, you can access the private members of the Date object like this:
// Create a date object
Date date(15, 2, 2004);

// Print the date in the format dd/mm/yyyy


cout << date.getDay() << "/" << date.getMonth() << "/" << date.getYear() << endl;
Solution:

 The two errors in the constructor definition are:


1. The parameters and instance variables have the same names, which causes
ambiguity.
2. The instance variable day is not initialized within the constructor.
 Corrected C++ code for the constructor:

Date(int y, int m, int d) {


year = y;
month = m;
day = d;
}

 The error in the line of code Date d; is that it’s trying to create an object of class Date
without passing any arguments, but there is no default constructor defined.
Solution:

 For part (e), I need to write a function that calculates the index of the day on which the
first of January for a given year falls. The index is based on the formula given in the
question, which uses the mod function and some arithmetic operations. Here is the C++
code for the function:

 // Define a mod function that returns a%b


 int mod(int a, int b) {
 return a - b * (a / b);
 }

 // Define a function that returns the index of the day on which the first of January for a
given year falls
 int firstDay(int year) {
 // Use the formula given in the question
 int first = mod(5 * mod(year - 1, 4) + 4 * mod(year - 1, 100) + 6 * mod(year - 1, 400),
7);
 // Return the index
 return first;
 }

 For part (f), I need to write a function named void calendar() that displays the calendar
for April 2022, as shown in the sample output. However, I need to code and execute these
functions to provide an accurate answer. Here is the C++ code for the function:
 // Define a function that displays the calendar for a given month and year
 void calendar(int month, int year) {
 // Declare an array of days in each month
 int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
 // Declare an array of names of each month
 string names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
 // Declare an array of names of each day
 string weekdays[7] = {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};

 // Check if the year is a leap year and adjust the days in February
 if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
 days[1] = 29;
 }

 // Print the calendar header
 cout << "Calendar for " << names[month - 1] << " " << year << endl;

 // Print the weekdays
 for(int i = 0; i < 7; i++) {
 cout << weekdays[i] << " ";
 }
 cout << endl;

 // Calculate the index of the first day of the month
 int first = firstDay(year);
 for(int i = 0; i < month - 1; i++) {
 first = (first + days[i]) % 7;
 }

 // Print the dates with proper alignment
 int date = 1;
 for(int i = 0; i < 6; i++) {
 for(int j = 0; j < 7; j++) {
 // Print spaces for the days before the first day of the month
 if(i == 0 && j < first) {
 cout << " ";
 // Print the date and increment it
 } else if(date <= days[month - 1]) {
 cout << date << " ";
 // Add an extra space for single digit dates
 if(date < 10) {
 cout << " ";
 }
 date++;
 // Print spaces for the days after the last day of the month
 } else {
 cout << " ";
 }
 }
 cout << endl;
 }
 }

Question 7:

Solution:
For part (a), the given C++ code initializes an integer variable x with 0 and then uses a for loop
to increment x by 2 each iteration until x is greater than 8. In each iteration, it checks if x % 4 is
not equal to 1; if true, it prints the value of x, otherwise, it prints “No”. The output would be
0
No
2
No
4
No
6
No

For part (b), here’s a sample C++ function that calculates and returns the average of an array:
#include <iostream>
using namespace std;

double average(int arr[], int size) {


int sum = 0;
for(int i =0; i < size; i++) {
sum += arr[i];
}
return static_cast<double>(sum) / size;
}

int main() {
int myArray[] = {1,2,3,4,5};
cout << "Average: " << average(myArray,5) << endl;
return 0;
}

Solution:
#include <iostream>
int main() {
int a0 = 1, b0 = 4;
int ai = a0, bi = b0;
int ni;

int i = 0;
do {
ni = ai - 1 * bi - 1 + ai - 1; // Calculating the value of ni based on the given formula
std::cout << "n" << i+1 << ": " << ni << std::endl; // Printing each value of ni

// Updating values of ai and bi for next iteration


ai += 2;
bi += 2;

i++;
} while (i < 10); // Looping until first ten numbers are displayed

return 0;
}

Solution:
#include <iostream>

int main() {
int num = 2; // Starting from the smallest positive even integer
int count = 0; // To keep track of the number of perfect numbers found

while (count < 4) {


int sum = 1; // Initialized to 1 as all numbers are divisible by 1
int i = 2;

// Loop to find all divisors of the number


while (i <= num / 2) {
if (num % i == 0) {
sum += i;
}
i++;
}

// Check if the number is a perfect number


if (sum == num) {
std::cout << num << " is a perfect number." << std::endl;
count++;
}

num++;
}

return 0;
}

Question 8:
Solution:

 For part (i), you can initialize the array names with months as follows:
 std::string names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"};

 For part (ii), you can write a function to initialize a month of the year as follows:
 int initializeMonth(int month) {
 if(month < 1 || month > 12) {
 return -1; // Invalid month
 }
 return month; // Valid month
 }

 For part (iii), you can write a function that returns the number of current month of the
year as follows:
 int currentMonth() {
 time_t t = time(0); // Get the current time
 tm* now = localtime(&t); // Convert it to local time structure
 return now->tm_mon + 1; // Return the month field (0-11) plus one
 }

 For part (iv), you can write a function that returns the name that corresponds to the
current month of the year as follows:
 std::string getMonthName(int month) {
 if(month < 1 || month > 12) {
 return ""; // Invalid month
 }
 std::string names[] =
{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; // Array
of month names
 return names[month - 1]; // Return the name at the corresponding index (0-11)
 }

 For part (v), you can write a function that returns the name of next month as follows:
 std::string getNextMonthName(int currentMonth) {
 if(currentMonth < 1 || currentMonth > 12) {
 return ""; // Invalid month
 }
 std::string names[] =
{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; // Array
of month names
 return names[currentMonth % 12]; // Return the name at the next index (0-11) using
modulo operator
 }

 For part (vi), you can write a function that returns the name of previous month as follows:
 std::string getPreviousMonthName(int currentMonth) {
 if(currentMonth < 1 || currentMonth > 12) {
 return ""; // Invalid month
 }
 std::string names[] =
{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; // Array
of month names
 int index = (currentMonth - 2 + 12) % 12; // Calculate the previous index (0-11) using
subtraction and modulo operator
 return names[index]; // Return the name at the previous index
 }

 For part (vi), you can write a function that returns the name of the previous month using
one decision-making construct as follows:
 std::string getPreviousMonthName(int currentMonth) {
 if(currentMonth < 1 || currentMonth > 12) {
 return ""; // Invalid month
 }
 std::string names[] =
{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; // Array
of month names
 int index = (currentMonth - 2 + 12) % 12; // Calculate the previous index (0-11) using
subtraction and modulo operator
 return names[index]; // Return the name at the previous index
 }

 For part (vii), you can write a function that adds one to the current month as follows:
 int addOneToCurrentMonth(int currentMonth) {
 if(currentMonth < 1 || currentMonth > 12) {
 return -1; // Invalid month
 }
 return (currentMonth + 1) % 12; // Add one and use modulo operator to get the next
month (0-11)
 }

 For part (viii), you can write a function that adds a number of months, received as a
parameter, to the current month and reuses the function defined in part (vii) as follows:
 int addMonthsToCurrentMonth(int currentMonth, int months) {
 if(currentMonth < 1 || currentMonth > 12) {
 return -1; // Invalid month
 }
 if(months < 0) {
 return -1; // Invalid number of months
 }
 int result = currentMonth; // Initialize the result with the current month
 for(int i = 0; i < months; i++) {
 result = addOneToCurrentMonth(result); // Reuse the function from part (vii) to add
one month at a time
 }
 return result; // Return the final result
 }

Question 9:
Solution:
int data[7] = {61, 12, 34, 50, 40, 67};
int i = 0;
while(true) {
if(data[i] == 50) {
break; // Break out of the loop when data[i] is 50
}
i += 1;
}
cout << data[i] << " found" << endl;
Solution:
Write a function that converts an angle in degrees to radians, using the given class definition and
formula. Here is the C++ code that does this:
#include <iostream>
#include <cmath> // for M_PI

class Trig {
private:
double x; // angle in degrees
public:
Trig(double angleInDegrees) : x(angleInDegrees) {}

double toRadians() {
return x * M_PI / 180.0;
}
};

int main() {
Trig trig(45); // example: 45 degrees
std::cout << "Angle in radians: " << trig.toRadians() << std::endl;

return 0;
}
#include <iostream>
#include <cmath> // for M_PI and sin

class Trig {
private:
double x; // angle in degrees
public:
Trig(double angleInDegrees) : x(angleInDegrees) {}

double toRadians() {
return x * M_PI / 180.0;
}

// (ii) non-recursive function that returns the factorial of an integer


int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

// (iii) function that calculates and returns the sin of an angle in degrees
double sinx() {
double rad = toRadians(); // convert angle to radians
double estimate = 0; // estimated sine value
double actual = sin(rad); // actual sine value from math library
double error = 0; // error between estimate and actual
int n = 0; // number of repetitions
do {
estimate += pow(-1, n) * pow(rad, 2 * n + 1) / factorial(2 * n + 1); // Taylor series
formula for sin(x)
error = abs(estimate - actual); // calculate error
n++; // increment n
} while (error > 0.0001); // repeat until error is less or equal to 10^-4
return estimate;
}

// (iv) function that calculates and returns the cosine of an angle in degrees
double cosx() {
double rad = toRadians(); // convert angle to radians
double estimate = 0; // estimated cosine value
for (int n = 0; n <= 10; n++) { // let n vary from 0 to 10
estimate += pow(-1, n) * pow(rad, 2 * n) / factorial(2 * n); // Taylor series formula for
cos(x)
}
return estimate;
}

// (v) function that displays the sine and cosine of angle x


void display() {
std::cout << "Angle in degrees = " << x << std::endl;
std::cout << "Angle in radians: " << toRadians() << std::endl;
std::cout << "cos(" << x << ")=" << cosx() << std::endl;
std::cout << "sin(" << x << ")=" << sinx() << std::endl;
}
};

int main() {
Trig trig(30); // example: 30 degrees
trig.display(); // display results

return 0;
}

Question 10:
Solution:
#include <iostream>
#include <string>
using namespace std;

class BirthDay {
private:
int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
string names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int day;
int month;
int year;
public:
// Set functions
BirthDay& setDay(int d) {
if(d > 0 && d <= days[month-1]) {
day = d;
} else {
cout << "Invalid day!" << endl;
}
return *this;
}

BirthDay& setMonth(int m) {
if(m >= 1 && m <= 12) {
month = m;
} else {
cout << "Invalid month!" << endl;
}
return *this;
}

BirthDay& setYear(int y) {
if(y >= 1000 && y <= 2010) {
year = y;

// Check for leap year and adjust February days


if((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
days[1] = 29;
else
days[1] = 28;

} else {
cout << "Invalid year!" << endl;
}

return *this;
}

// Get functions
int getDay() const { return day; }
int getMonth() const { return month; }
string getMonthName() const { return names[month-1]; }
int getYear() const { return year; }
};

int main() {

// Example usage
BirthDay bday;

bday.setYear(2004).setMonth(2).setDay(29);

cout << bday.getDay() << "-"


<< bday.getMonthName() << "-"
<< bday.getYear() << endl;

return 0;

}
Solution:
© (i) Two errors in the constructor definition are:

 The constructor name should be BirthDay, not Date, to match the class name.
 The assignment day = day; does not assign the parameter value to the instance variable. It
should be this->day = day; or the parameter name should be different from the instance
variable name.

(ii) Two errors in the line of code written in the main function are:

 The constructor BirthDay(int, int, int) expects three arguments, but only one is provided.
This causes a compile-time error.
 The variable name b is different from the class name Birthday. C++ is case-sensitive, so
this causes a name lookup error.

(d) A possible definition of the function void leap() is:


void leap() {
// Check for leap year and adjust February days
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
days[1] = 29;
else
days[1] = 28;
}
(e) A possible definition of the function string toString() is:
#include <string>
using namespace std;

string toString() {
// Initialize the string variable
string s = "";

// Append the day to the string


s += to_string(day);

// Append a dash to the string


s += "-";

// Append the month name to the string


s += getMonthName();

// Append another dash to the string


s += "-";

// Append the year to the string


s += to_string(year);

// Return the string


return s;
}

(f) A possible definition of the function int firstMonth() is:


#include <iostream>
using namespace std;

int firstMonth() {
// Initialize the first index
int first = (5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7;

// Use a while loop to add the number of days in each month before the given month
int i = 1;
while (i < month) {
// Add the number of days in each month
if (i == 2) {
// Check for leap year and adjust February days
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
first += 29;
else
first += 28;
} else if (i == 4 || i == 6 || i == 9 || i == 11) {
first += 30;
} else {
first += 31;
}

// Increment the month index


i++;
}

// Find the remainder of dividing the total days by 7


first = first % 7;
// Return the first index
return first;
}

(g)

#include <iostream>
#include <iomanip>
using namespace std;

void calendar() {
// Initialize the month and year
int month = 4;
int year = 2023;

// Calculate the index of the first day of the month using the formula given in part (f)
int first = (5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7;
for (int i = 1; i < month; i++) {
// Add the number of days in each month before the given month
if (i == 2) {
// Check for leap year and adjust February days
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
first += 29;
else
first += 28;
} else if (i == 4 || i == 6 || i == 9 || i == 11) {
first += 30;
} else {
first += 31;
}
}
// Find the remainder of dividing the total days by 7
first = first % 7;

// Display the calendar header


cout << "Calendar Apr\n";
cout << "Mo Tu We Th Fr Sa Su\n";

// Display the blank spaces before the first day


for (int i = 0; i < first; i++) {
cout << " ";
}
// Initialize the day counter
int day = 1;

// Use a do-while loop to display the days of the month


do {
// Print the day with a space
cout << setw(2) << day << " ";

// Increment the day and the first index


day++;
first++;

// If the first index reaches 7, start a new line


if (first == 7) {
cout << "\n";
first = 0;
}

// Repeat the loop until the day exceeds 30


} while (day <= 30);

// End the output with a new line


cout << "\n";
}

int main() {

// Example usage
calendar();

return 0;
}

Question 11:
Solution:
#include <iostream>
#include <vector>
#include <cmath>

// Function to calculate mean using a for loop


double calculateMean(const std::vector<double>& data) {
double sum = 0.0;
int size = data.size();

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


sum += data[i];
}

return sum / size;


}

// Function to calculate standard deviation using a do...while loop, reusing the calculateMean
function
double calculateStandardDeviation(const std::vector<double>& data) {
double mean = calculateMean(data);
double sum = 0.0;
int size = data.size();

int i = 0;

do {
sum += pow(data[i] - mean, 2);
++i;

} while(i < size);

return sqrt(sum / size);


}

int main() {
std::vector<double> dataset {1,2,3,4,5}; // Example dataset

std::cout << "Mean: " << calculateMean(dataset) << std::endl;


std::cout << "Standard Deviation: " << calculateStandardDeviation(dataset) << std::endl;

return 0;
}
Solution:
For the first part (b), the output of the provided code will be:
0 1 2 3 No!

For the second part ©, here is a possible C++ program that finds all perfect numbers less than
10,000 and displays them along with their factors:
#include <iostream>
using namespace std;

// A function to check if a number is perfect


bool isPerfect(int n) {
int sum = 0; // To store the sum of divisors
for (int i = 1; i < n; i++) {
if (n % i == 0) // If i is a divisor of n
sum += i; // Add i to the sum
}
return (sum == n); // Return true if sum equals n
}

// A function to print the factors of a number


void printFactors(int n) {
for (int i = 1; i < n; i++) {
if (n % i == 0) // If i is a factor of n
cout << i << "+"; // Print i with a plus sign
}
cout << "=" << n << endl; // Print = and n with a newline
}

int main() {
int n = 2; // The starting number
do {
if (isPerfect(n)) { // If n is a perfect number
printFactors(n); // Print its factors
}
n++; // Increment n by 1
} while (n < 10000); // Repeat until n reaches 10000
return 0;
}
Question 12:

Solution:
For the first part (a)(i), a line of code that initializes the array names with names shown in Figure
1 is:
string names[7] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

For the second part (a)(ii), the definition of a function that will initialize day of the week is:
void initDay(int& day) {
cout << "Enter a number between 1 and 7: ";
cin >> day;
if (day < 1 || day > 7) // If the day is out of specified range
day = 1; // Initialize day to 1
}

For the third part (a)(iii), the definition of the function that returns the name that corresponds to
the current day of the week is:
string getName(int day) {
return names[day - 1]; // Return the name at the index of day - 1
}

For the fourth part (a)(iv), the definition of the function int when(int) such that it returns name of
the day, x days after current day is:
string when(int x) {
int next = (day + x) % 7; // Calculate the next day after x days
if (next == 0) // If the next day is 0
next = 7; // Set it to 7
return names[next - 1]; // Return the name at the index of next - 1
}

Solution:
For the first question (b), a possible solution to rewrite the loop without using the keyword
“break” is
int data[7] = {61, 12, 34, 50, 40, 67};
int i = 5;
while(i > -1 && data[i] != 89) {
i--;
}
if(i > -1) {
cout << data[i] << " found\n";
}

For the second question ©, a possible solution to write the class definitions for Shape2D and
Rectangle is:
// A class to model a 2D shape
class Shape2D {
private:
string name; // The name of the shape
public:
// A constructor that takes the name as a parameter
Shape2D(string n) {
name = n;
}
// A getter method that returns the name of the shape
string getName() {
return name;
}
};

// A class to model a rectangle


class Rectangle : public Shape2D {
private:
double length; // The length of the rectangle
double width; // The width of the rectangle
public:
// A constructor that takes the name, length, and width as parameters
Rectangle(string n, double l, double w) : Shape2D(n) {
length = l;
width = w;
}
// A method that returns the area of the rectangle
double getArea() {
return length * width;
}
// A method that returns the perimeter of the rectangle
double getPerimeter() {
return 2 * (length + width);
}
};
Question 13:

Solution:
#include <iostream>
#include <cmath>

class Log {
private:
double x;
public:
// i. Definition of function void setX(double)
void setX(double value) {
if (value > 0.0 && value < 1.0) {
x = value;
} else {
std::cerr << "Value must be between 0 and 1." << std::endl;
}
}

// ii. Definition of get function for instance variable x


double getX() const {
return x;
}

// iii. Using a while loop, definition of a function double log_mX()


double log_mX() const {
double result = 0;
double term;
int n = 1;

do {
term = pow(-1, n+1) * pow(x, n) / n;
result += term;
n++;
} while (fabs(term) > 1e-6); // or another small number as the tolerance level

return result;
}

// iv. Using a do...while loop, definition of a function double log_pX()


double log_pX() const {
if (x >= -1 && x <= 1) {
double result = 0;
int i = 1;
double term;

do {
term = pow(x, i)/i;
if(i%2 == 0) {
result -= term;
} else {
result += term;
}
i++;

} while(fabs(term/result)>pow(10,-6));

return result;

} else {
std::cerr << "Value must be between -1 and +1." << std::endl;
return NAN;
}
}
};

Solution:
#include <iostream>
#include "Log.h" // Assuming the class Log is defined in a separate header file

using namespace std;

int main() {
Log log; // Create an object of the class Log
double x; // Declare a variable to store the input value
cout << "Enter value of x: "; // Prompt user to enter value for x
cin >> x; // Read the input value
if (x > 0.0 && x < 1.0) { // If x is between 0 and 1
log.setX(x); // Call the setX function to initialize x
cout << "ln(1 + " << x << ") = " << log.log_pX() << endl; // Display ln(1 + x)
cout << "ln(1 - " << x << ") = " << log.log_mX() << endl; // Display ln(1 - x)
} else { // If x is not between 0 and 1
cerr << "Input should be greater than 0 and less than 1." << endl; // Display error message
return 1; // Exit with a non-zero status
}
return 0; // Exit with a zero status
}

Question 14:

Solution:
#include <iostream>
#include <cmath>

// A function that estimates and returns the value of pi using the formula
double estimatePi() {
double pi = 2; // The initial value of pi
double term = 2; // The initial value of the term
double root = sqrt(2); // The initial value of the square root
while (term > 1) { // While the term is greater than 1
term = 2 / root; // Update the term
pi *= term; // Multiply the term to pi
root = sqrt(2 + root); // Update the square root
}

return pi; // Return the estimated value of pi


}

int main() {
std::cout << "The estimated value of pi is " << estimatePi() << std::endl; // Display the result
return 0;
}

Solution:
// i. Write a function that returns the name of the day on which first January falls for a year stored
in variable year
string firstDay(int year) {
int first = (5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7; //
Calculate the index of the first day
return days[first]; // Return the name of the day at the index
}

// ii. Write a function that returns index of the day on which a birth day falls(birth day is stored in
variable bday)
int bdayIndex(int bday, int month, int year) {
int index = firstDay(year); // Get the index of the first day of the year
for (int i = 0; i < month - 1; i++) { // Loop through the months before the birth month
index += mons[i]; // Add the number of days in each month to the index
if (i == 1 && isLeap(year)) // If the month is February and the year is a leap year
index++; // Add one more day to the index
}
index += bday - 1; // Add the number of days before the birth day to the index
index %= 7; // Mod the index by 7 to get the index of the birth day
return index; // Return the index of the birth day
}

// iii. Write definition of a function that displays the calendars of the birth month, the month
before and the month after for the year given in variable year
void displayCalendars(int bday, int month, int year) {
int prev = month - 1; // The index of the previous month
int next = month + 1; // The index of the next month
int prevYear = year; // The year of the previous month
int nextYear = year; // The year of the next month
if (prev == 0) { // If the previous month is December of the previous year
prev = 12; // Set the previous month to 12
prevYear--; // Decrement the previous year by 1
}
if (next == 13) { // If the next month is January of the next year
next = 1; // Set the next month to 1
nextYear++; // Increment the next year by 1
}
int prevDays = mons[prev - 1]; // The number of days in the previous month
int nextDays = mons[next - 1]; // The number of days in the next month
if (isLeap(prevYear) && prev == 2) // If the previous year is a leap year and the previous
month is February
prevDays++; // Add one more day to the previous month
if (isLeap(nextYear) && next == 2) // If the next year is a leap year and the next month is
February
nextDays++; // Add one more day to the next month
int prevStart = bdayIndex(1, prev, prevYear); // The index of the first day of the previous
month
int nextStart = bdayIndex(1, next, nextYear); // The index of the first day of the next month
cout << "The calendars of the birth month, the month before and the month after are:\n\n"; //
Display the header
cout << names[prev - 1] << " " << prevYear << endl; // Display the name and the year of the
previous month
cout << "Mon Tue Wed Thu Fri Sat Sun\n"; // Display the names of the days
for (int i = 0; i < prevStart; i++) { // Loop through the empty spaces before the first day of the
previous month
cout << " "; // Print four spaces for each empty space
}
for (int i = 1; i <= prevDays; i++) { // Loop through the days of the previous month
cout << i << " "; // Print the day with two spaces
if (i < 10) cout << " "; // Print an extra space if the day is a single digit
if ((prevStart + i) % 7 == 0) cout << endl; // Print a newline if the day is the last of the week
}
cout << "\n\n"; // Print two newlines to separate the calendars
cout << names[month - 1] << " " << year << endl; // Display the name and the year of the
birth month
cout << "Mon Tue Wed Thu Fri Sat Sun\n"; // Display the names of the days
int start = bdayIndex(1, month, year); // The index of the first day of the birth month
for (int i = 0; i < start; i++) { // Loop through the empty spaces before the first day of the birth
month
cout << " "; // Print four spaces for each empty space
}
for (int i = 1; i <= mons[month - 1]; i++) { // Loop through the days of the birth month
if (i == bday) cout << "*"; // Print an asterisk if the day is the birth day
else cout << " "; // Print a space otherwise
cout << i << " "; // Print the day with two spaces
if (i < 10) cout << " "; // Print an extra space if the day is a single digit
if ((start + i) % 7 == 0) cout << endl; // Print a newline if the day is the last of the week
}
cout << "\n\n"; // Print two newlines to separate the calendars
cout << names[next - 1] << " " << nextYear << endl; // Display the name and the year of the
next month
cout << "Mon Tue Wed Thu Fri Sat Sun\n"; // Display the names of the days
for (int i = 0; i < nextStart; i++) { // Loop through the empty spaces before the first day of the
next month
cout << " "; // Print four spaces for each empty space
}
for (int i = 1; i <= nextDays; i++) { // Loop through the days of the next month
cout << i << " "; // Print the day with two spaces
if (i < 10) cout << " "; // Print an extra space if the day is a single digit
if ((nextStart + i) % 7 == 0) cout << endl; // Print a newline if the day is the last of the week
}
cout << "\n"; // Print a newline at the end
}

// A helper function that checks if a year is a leap year


bool isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); // Return true if the year is
divisible by 4 and not by 100, or by 400
}

Question 15:
Solution:

 The main function creates a playlist with four sample songs.


 Each song has an index and a title.
 The circular linked list ensures that the last song points back to the first song, allowing
the playlist to restart.

#include <iostream>
#include <string>

class Song {
private:
int index;
std::string title;
Song* nextSong;

public:
Song(int idx = 0, const std::string& t = "", Song* next = nullptr)
: index(idx), title(t), nextSong(next) {}

// Setters
void setIndex(int idx) { index = idx; }
void setTitle(const std::string& t) { title = t; }
void setNext(Song* next) { nextSong = next; }

// Getters
int getIndex() const { return index; }
const std::string& getTitle() const { return title; }
Song* getNext() const { return nextSong; }
};

class PlayList {
private:
Song* firstSong;

public:
PlayList() : firstSong(nullptr) {}

// Add a song to the playlist


void addSong(const Song& song) {
if (!firstSong) {
firstSong = new Song(song.getIndex(), song.getTitle());
firstSong->setNext(firstSong); // Circular reference for playlist restart
} else {
Song* lastSong = firstSong;
while (lastSong->getNext() != firstSong) {
lastSong = lastSong->getNext();
}
lastSong->setNext(new Song(song.getIndex(), song.getTitle(), firstSong));
}
}

// Print details of all songs in the playlist


void printList() const {
Song* currentSong = firstSong;
do {
std::cout << "Song " << currentSong->getIndex() << ": " << currentSong->getTitle() <<
std::endl;
currentSong = currentSong->getNext();
} while (currentSong != firstSong);
}

// Other functions (e.g., removeSong, getNextSong, etc.) can be added as needed


};

int main() {
PlayList myPlaylist;

// Create sample songs


myPlaylist.addSong(Song(1, "Zuena"));
myPlaylist.addSong(Song(2, "Badder Dan"));
myPlaylist.addSong(Song(3, "Yatapita by Diamond"));
myPlaylist.addSong(Song(4, "Baby Calm Down"));

std::cout << "Playlist contents:" << std::endl;


myPlaylist.printList();
return 0;
}

Question 16:

Solution:
#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
std::srand(std::time(0));

int wheel1 = std::rand() % 10 + 1;


int wheel2 = std::rand() % 10 + 1;
int wheel3 = std::rand() % 10 + 1;

std::cout << "Wheel 1 -> " << wheel1 << std::endl;


std::cout << "Wheel 2 -> " << wheel2 << std::endl;
std::cout << "Wheel 3 -> " << wheel3 << std::endl;

if (wheel1 == wheel2 && wheel2 == wheel3) {


std::cout << "Payout is 80" << std::endl;
} else if (wheel1 == wheel2 || wheel2 == wheel3 || wheel1 == wheel3) {
if ((wheel1 != wheel2 && (abs(wheel2 - wheel1) == 1 || abs(wheel2 - wheel1) == 9)) ||
(wheel3 != wheel2 && (abs(wheel3 - wheel2) == 1 || abs(wheel3 - wheel2) == 9)) ||
(abs(wheel3 - wheel1) == 1 || abs(wheel3 - wheel1) == 9)) {
// Consecutive numbers
std::cout << "Payout is: 16" << std::endl;
} else {
// Two wheels display the same number
std::cout << "Payout is: 16" << std::endl;
}
} else {
std::cout << "Payout is 0" << std::endl;
}

return 0;
}

Question 17:
Solution:
#include<iostream>
#include<string>
using namespace std;
string days[7] = {"Mon", "Tue", "Wed", "Thu", "Fri","Sat","Sun"};
string names[12] = {"Jan", "Feb", "Mar", "Apr", "May" , "Jun" , "Jul" ,
"Aug" , "Sep" , "Oct" , "Nov" ,"Dec"};
int mons [12] = {31,28,31,30,31,30,31,31,30 ,31 ,30 ,31};
int bday,bmonth,year;

// Function to return the name of the day on which first January falls
// for a year stored in variable year
string firstJanDay(int year) {
// Calculate the index of the day using the formula given
int first = (5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7;
// Return the corresponding name from the days array
return days[first];
}

// Function to return the index of the day on which birth day falls
// (birth day is stored in variable bday)
int birthdayDay(int bday, int bmonth, int year) {
// Check if the year is a leap year and adjust the number of days in February
if (year % 4 == 0) {
mons[1] = 29;
} else {
mons[1] = 28;
}
// Calculate the total number of days from January 1 to the birth day
int total = bday;
for (int i = 0; i < bmonth - 1; i++) {
total += mons[i];
}
// Calculate the index of the day using the formula given
int first = (5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7;
// Return the index of the day by adding the total and the first and taking the modulo 7
return (total + first) % 7;
}

// Function to return the name of the month in which the birth day falls
// (birth month is stored in variable bmonth)
string birthdayMonth(int bmonth) {
// Return the corresponding name from the names array
return names[bmonth - 1];
}

int main() {
// Input the birth day, month, and year
cout << "Enter your birth day: ";
cin >> bday;
cout << "Enter your birth month: ";
cin >> bmonth;
cout << "Enter your birth year: ";
cin >> year;

// Call the functions and display the results


cout << "The name of the day on which first January falls for " << year << " is " <<
firstJanDay(year) << endl;
cout << "The index of the day on which your birth day falls is " << birthdayDay(bday,
bmonth, year) << endl;
cout << "The name of the month in which your birth day falls is " << birthdayMonth(bmonth)
<< endl;

return 0;
}

Question 18:

Solution:
#include <iostream>
#include <array>
#include <cmath>

void softmax(std::array<double, 5>& arr) {


double sum = 0;
for(int i = 0; i < arr.size(); i++) {
arr[i] = std::exp(arr[i]);
sum += arr[i];
}

for(int i = 0; i < arr.size(); i++) {


arr[i] /= sum;
}
}

int main() {
std::array<double, 5> arr {6, 8, 2, 1, 3};

softmax(arr);

for(double i : arr) {
std::cout << i << " ";
}

return 0;
}
Solution:

 Convert degrees to radians:


 #include <iostream>
 #include <cmath>

 template<typename T>
 T toRadians(T degrees) {
 const double pi = 3.14159;
 return degrees * pi / 180;
 }

 Calculate sine using a do…while loop:
 template<typename T>
 T calculateSine(T degrees) {
 const double pi = 3.14159;
 T radians = toRadians(degrees);
 T term = radians, sum = term;
 int n = 1;

 do {
 term *= -radians * radians / ((2 * n) * (2 * n + 1));
 sum += term;
 n++;
 } while (std::abs(term) > 0.001);

 return sum;
 }

 Calculate cosine using a while loop:


 template<typename T>
 T calculateCosine(T degrees) {
 const double pi = 3.14159;
 T radians = toRadians(degrees);
 T term = 1, sum = term;
 int n = 0;

 while(n <10){
 term *= -radians * radians / ((2 * n + 1) * (2 * n + 2));
 sum += term;
 n++;
 }

 return sum;
 }

Question 19:
Solution:
(i) To insert 16 as the 7th element of data_1 without using subscript [] operator:
 data_1.insert(data_1.begin() + 6, 16);
(ii) To swap the two vectors:
data_1.swap(data_2);
Using range-based for loop to display elements of data_2 after swapping:
for(int i : data_2)
cout << i << " ";

The output will be: 4 5 7 9

NOTE: ANSWERS MAY NOT BE 100% ACCURATE


Prepared by crispusjoash
@crispusjoash on all platforms

You might also like