Here are the answers to the questions provided in the image, based on the principles of C++
programming.
Question 1 (15 marks)
a. Explain the concept of classes and objects in C++ (6 marks)
● Classes: A class is a user-defined blueprint or template for creating objects. It
encapsulates data (member variables) and functions (member methods) that operate on
that data. A class doesn't occupy memory until an object is created from it. Think of a
class as a plan for a house; it defines the number of rooms, windows, and doors, but it
isn't the physical house itself.
● Objects: An object is an instance of a class. It is a concrete entity created from the class
blueprint. When an object is created, it allocates memory to hold its own unique set of
data members. Using the house analogy, an object is the actual physical house built from
the class blueprint. Each object has its own state (the values of its variables) and behavior
(the functions it can perform).
b. Discuss the principles of encapsulation as an OOP concept (5 marks)
Encapsulation is the bundling of data and the methods that operate on that data into a single
unit (the class). It's a fundamental principle of Object-Oriented Programming (OOP) that
achieves two main goals:
1. Data Hiding: It hides the internal state of an object from the outside world. The data
members of a class are typically declared as private, meaning they can only be accessed
and modified by the member functions of the same class. This prevents direct,
uncontrolled manipulation of the data.
2. Controlled Access: Encapsulation provides a controlled interface (public methods)
through which the outside world can interact with the object's data. This ensures that the
data is always in a valid state because it can only be changed by the object's own
methods, which can include validation logic.
c. Enumerate four fundamental data types in C++ (4 marks)
1. int: Used to store integer values (e.g., 5, -100).
2. char: Used to store single characters (e.g., 'A', 'g', '7').
3. float: Used to store single-precision floating-point numbers (e.g., 3.14, -0.005).
4. double: Used to store double-precision floating-point numbers, offering more precision
than float (e.g., 1.79769e+308).
Question 2 (15 marks)
a. Explain the concept of inheritance in C++ (4 marks)
Inheritance is a mechanism in C++ where a new class (the "derived" or "child" class) is created
from an existing class (the "base" or "parent" class). The derived class inherits the properties
(member variables) and behaviors (member functions) of the base class. This promotes code
reusability and establishes a "is-a" relationship between the classes. For example, a Car class
and a Truck class can both inherit from a base Vehicle class, sharing common attributes like
speed and fuelType.
b. Describe the basic C++ command enabling users to print messages on the screen and
give an example of its use (6 marks)
The basic command for printing messages to the standard output (the screen) in C++ is
std::cout. It is an object of the ostream class, and it is used with the stream insertion operator
<<. This operator "sends" data to the cout object, which then displays it.
Example:
#include <iostream>
int main() {
std::cout << "Hello, World!";
std::cout << "The year is " << 2025 << ".";
return 0;
}
Explanation: The first line prints the string literal "Hello, World!". The second line demonstrates
printing a string followed by an integer.
c. Explain the phrase "precedence of operators" with an example (5 marks)
Operator precedence determines the order in which operators in an expression are evaluated.
When an expression contains multiple operators, the one with the higher precedence is
evaluated first. For example, multiplication (*) and division (/) have higher precedence than
addition (+) and subtraction (-). If operators have the same precedence, their associativity
(left-to-right or right-to-left) determines the order of evaluation.
Example:
int result = 5 + 3 * 2;
In this expression, the multiplication 3 * 2 will be performed first because * has higher
precedence than +.
1. 3 * 2 is evaluated, resulting in 6.
2. The expression becomes 5 + 6.
3. The addition is performed, and result is assigned the value 11.
If there were no precedence rules, one might incorrectly calculate it as (5 + 3) * 2, which would
yield 16.
Question 3 (15 marks)
a. Explain the concept of polymorphism in C++ (4 marks)
Polymorphism, meaning "many forms," is the ability of an object to take on many forms. In C++,
it allows objects of different classes that are related through inheritance to respond to the same
function call in their own specific ways. This is typically achieved through virtual functions and
function overloading. It allows for a single interface to represent different underlying forms. For
example, a draw() function can be called on an object of type Shape, but the specific version of
draw() that runs depends on whether the object is a Circle, Square, or Triangle.
b. Identify five good programming styles (5 marks)
1. Meaningful Variable and Function Names: Use descriptive names like studentName
instead of s and calculateAverage instead of calc.
2. Code Indentation and Formatting: Use consistent indentation (e.g., 4 spaces) to clearly
show the structure of code blocks.
3. Comments: Add comments to explain complex logic, non-obvious code, or to describe
the purpose of functions and classes.
4. Modularization: Break down large problems into smaller, manageable functions or
classes. Each function should ideally perform a single, well-defined task.
5. Use of Constants: Use const variables for values that do not change (e.g., const double
PI = 3.14159;). This improves readability and prevents accidental modification.
c. Write short notes on three of the identified styles in question 3b (6 marks)
1. Meaningful Variable and Function Names: This practice makes code self-documenting.
When a variable is named customerAge and a function is named calculateShippingCost(),
it's immediately clear what they represent and do, without the need for excessive
comments. This greatly improves code readability and maintainability, especially in large
projects with multiple developers.
2. Code Indentation and Formatting: Consistent indentation is crucial for visual clarity. It
helps programmers quickly identify the scope of loops, if statements, and functions.
Proper formatting prevents errors by making it easy to see where code blocks begin and
end, reducing the chances of misplaced braces or other syntax errors.
3. Comments: While meaningful names and good formatting are key, comments are
essential for explaining why certain decisions were made or how a complex algorithm
works. They provide context that the code alone may not convey. However, good style
dictates that comments should explain the "what" and "why," not just the obvious "how" of
a piece of code.
Question 4 (15 marks)
a. Write a short note on the concept that changed the linear sequence of executing
instructions in C++ (6 marks)
The concept that changed the linear sequence of executing instructions is control flow. Control
flow statements are programming constructs that allow a program to make decisions
(branching) or repeat a block of code (looping). Without control flow, instructions would simply
execute one after another in a straight line.
● Selection statements (if, if-else, switch) allow the program to choose which block of
code to execute based on a condition.
● Iteration statements (for, while, do-while) allow a block of code to be executed
repeatedly as long as a condition is met.
b. What is the difference between if-then and if-then-else statements? Explain with
examples (5 marks)
● if-then statement: This is a basic conditional statement that executes a block of code
only if a specified condition is true. If the condition is false, the program simply skips the
code block and continues to the next statement. Example:
int age = 20;
if (age >= 18) {
std::cout << "You are an adult.";
}
If age is less than 18, nothing is printed.
● if-then-else statement: This statement provides a way to execute one block of code if
the condition is true and a different block of code if the condition is false. It guarantees
that one of the two blocks will always be executed. Example:
int age = 16;
if (age >= 18) {
std::cout << "You are an adult.";
} else {
std::cout << "You are a minor.";
}
Since the condition age >= 18 is false, the code in the else block is executed, and "You
are a minor." is printed.
c. State four rules guiding the naming and use of identifiers in C++ (4 marks)
1. Start with a letter or an underscore: An identifier must begin with either a letter (a-z,
A-Z) or an underscore (_). It cannot start with a digit.
2. Can contain letters, digits, and underscores: After the first character, an identifier can
consist of any combination of letters, digits (0-9), and underscores.
3. Case-sensitive: C++ is a case-sensitive language. myVariable, myvariable, and
MyVariable are all considered different identifiers.
4. Cannot be a C++ keyword: Identifiers cannot be a reserved C++ keyword, such as int, if,
for, class, etc.
Question 5 (15 marks)
a. Explain the concept of operator overloading in C++ (3 marks)
Operator overloading is a feature in C++ that allows you to redefine or "overload" the
functionality of built-in operators (like +, -, *, ==) for user-defined types (classes). This allows
you to use these operators with objects of your classes in a natural and intuitive way. For
example, you could overload the + operator to add two objects of a ComplexNumber class
together.
b. Explain three general principles of good programming (6 marks)
1. Readability: Code should be easy to read and understand. This is achieved through clear
variable names, consistent formatting, and well-placed comments. Readable code is
easier to debug and maintain.
2. Maintainability: Code should be easy to modify, update, and fix. This is a direct
consequence of readability and modularity. If code is well-structured and documented, it's
easier for developers to find and change specific parts without introducing new bugs.
3. Efficiency: Code should perform its task using the least amount of computational
resources (time and memory) possible, without sacrificing clarity. This involves choosing
appropriate algorithms and data structures for the problem at hand. It's important to
balance efficiency with readability and maintainability.
c. Differentiate between Local and Global variables with an illustration (6 marks)
Feature Local Variables Global Variables
Scope Defined inside a function or a Defined outside all functions.
block. Accessible only within Accessible from anywhere in
that function/block. the program.
Lifetime Created when the Created when the program
function/block is entered and starts and destroyed when the
destroyed when it is exited. program terminates.
Initialization Not automatically initialized; Automatically initialized to zero
they contain garbage values by by the compiler if not explicitly
default. initialized.
Illustration:
#include <iostream>
int globalVar = 10; // Global variable
void myFunction() {
int localVar = 5; // Local variable
std::cout << "Inside myFunction: " << std::endl;
std::cout << "Local variable: " << localVar << std::endl;
std::cout << "Global variable: " << globalVar << std::endl;
} // localVar is destroyed here
int main() {
// std::cout << localVar; // This would cause a compilation error
std::cout << "Inside main: " << std::endl;
std::cout << "Global variable: " << globalVar << std::endl;
myFunction();
return 0;
} // globalVar is destroyed here when the program ends
In this example, globalVar is accessible from both main and myFunction. However, localVar is
only accessible inside myFunction. An attempt to access localVar from main would result in a
compiler error.
Question 6 (15 marks)
a. What are Comments in C++? Discuss the types of Comments in C++ (4 marks)
Comments are non-executable text within a program's source code. They are ignored by the
compiler and are used by programmers to explain the code, making it more understandable.
There are two main types of comments in C++:
1. Single-line comments: These start with a double slash (//). Everything from the // to the
end of the line is a comment. Example: int x = 5; // This is a single-line comment
2. Multi-line comments (or Block comments): These start with /* and end with */.
Everything between these two delimiters is treated as a comment, even if it spans multiple
lines. Example:
/*
This is a multi-line comment.
It can be used to describe a function's purpose
or a complex block of code.
*/
b. Enumerate five application areas of object-oriented programming languages (5 marks)
1. Game Development: OOP is used extensively in game engines to represent game
entities like characters, enemies, and items as objects, each with their own properties and
behaviors.
2. Simulation and Modeling: It is used to model real-world systems, such as traffic flow,
weather patterns, or financial markets, by creating objects that represent the components
of the system.
3. GUI (Graphical User Interface) Design: Elements of a GUI, such as buttons, text boxes,
and windows, are naturally represented as objects in OOP.
4. Database Management Systems (DBMS): OOP can be used to represent database
records and schemas as objects, simplifying interaction with the data.
5. Operating Systems: OOP principles help in the design of operating systems by treating
system components (e.g., files, processes, devices) as objects.
c. Write a C++ program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user (6 marks)
#include <iostream>
// Function to check if a number is prime
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int n;
// Get the upper limit from the user
std::cout << "Enter a positive integer n to find prime numbers up
to n: ";
std::cin >> n;
// Validate the input
if (n < 1) {
std::cout << "Invalid input. Please enter a positive integer."
<< std::endl;
return 1;
}
std::cout << "Prime numbers between 1 and " << n << " are:" <<
std::endl;
// Loop through numbers from 2 to n and check for primality
for (int i = 2; i <= n; ++i) {
if (isPrime(i)) {
std::cout << i << " ";
}
}
std::cout << std::endl;
return 0;
}
Explanation:
● The isPrime() function takes an integer and returns true if it is a prime number and false
otherwise. It efficiently checks for divisibility up to the square root of the number.
● The main() function prompts the user for a value n.
● It then loops from 2 up to n, calling isPrime() for each number.
● If isPrime() returns true, the number is printed to the console.