Lab Guide - Programming
Lab Guide - Programming
Year 1
PROGRAMMING
Lab Guide
Developed by
Michael R Chinguwo
COPYRIGHT
Copyright© 2025 by Michael R Chinguwo. All rights reserved.
ii
C++ PROGRAMMING LAB GUIDE
This guide provides a structured approach to solving C++ programming problems. Focus on
understanding the concepts rather than directly searching for solutions. For each question, follow
the steps.
iii
TABLE OF CONTENTS
iv
4.5 Display Numbers from 0 to 1000 in Steps of 10 ................................................................ 17
4.6 Multiply by 2 Until the Number Exceeds 50 ..................................................................... 17
4.7 Sum of All Even Numbers Between 1 and 100 .................................................................. 18
4.8 Sum of Digits Using a Do-While Loop .............................................................................. 18
4.9 Factorial Using a For Loop ................................................................................................ 19
4.10 Reverse a Number Using a While Loop ........................................................................... 19
4.11 Sum of All Prime Numbers Between 1 and 100 ............................................................... 20
LAB 5: PROGRAM CONTROL STRUCTURES IV.............................................................. 21
5.1 Sum of Integers Up to a Given Number ............................................................................. 21
5.2 Lake Malawi Rising Table.................................................................................................. 21
5.3 Doubling Salary Table ........................................................................................................ 22
5.4 Vehicle Distance Traveled .................................................................................................. 23
5.5 Compound Interest Calculation .......................................................................................... 24
5.6 Factorial Calculation Without Predefined Functions ......................................................... 25
5.7 Sales Bar Graph .................................................................................................................. 25
LAB 6: FUNCTIONS I ............................................................................................................... 27
6.1 Finding the Square Root of a Given Number ..................................................................... 27
6.2 Calculating the Power of a Number ................................................................................... 27
6.3 Rounding a Floating-Point Number ................................................................................... 28
6.4 Calculating Logarithms ...................................................................................................... 29
6.5 Convert Lowercase to Uppercase ....................................................................................... 29
6.6 Calculate Absolute Value .................................................................................................... 30
6.7 Check if a Character is a Digit ........................................................................................... 30
6.8 Trigonometric Functions of an Angle in Radians............................................................... 31
6.9 Generate and Print Five Random Numbers ........................................................................ 32
6.10 Guess the Random Number Game .................................................................................... 32
LAB 7: FUNCTIONS II ............................................................................................................. 33
7.1 Add Two Integers Using a Function ................................................................................... 33
7.2 Calculate the Area of a Circle............................................................................................. 33
7.3 Calculate the Cube of a Number ........................................................................................ 34
7.4 Find the Maximum of Two Numbers ................................................................................. 34
7.5 Check if a Number is Even................................................................................................. 35
7.6 Calculate the Factorial of a Number................................................................................... 35
v
7.7 Calculate Power Using a Function ..................................................................................... 36
7.8 Addition and Multiplication Functions .............................................................................. 36
7.9 Maximum, Minimum, and Average of Three Numbers ..................................................... 37
LAB 8: FUNCTIONS III ............................................................................................................ 38
8.1 Calculate Circle Area Using Inline Function ..................................................................... 38
8.2 Recursive Function to Sum Integers .................................................................................. 38
8.3 Iterative Function to Sum Integers ..................................................................................... 39
8.4 Triple an Integer Using Two Alternate Functions .............................................................. 39
8.5 Overloaded Functions for Shape Area Calculation ............................................................ 40
8.6 Recursive Factorial Function.............................................................................................. 41
8.7 Recursive Fibonacci Function ............................................................................................ 41
8.8 Recursive Function to Compute GCD................................................................................ 42
LAB 9: FUNCTIONS IV ............................................................................................................ 43
9.1 Arithmetic Functions Using Header File............................................................................ 43
9.2 Utility Functions Using Header File .................................................................................. 43
9.3 Calculate Rectangle Perimeter ........................................................................................... 44
9.4 Factorial Using Header and Source Files ........................................................................... 44
9.5 Math Operations Header File ............................................................................................. 45
9.6 Calculator Using Header File ............................................................................................. 45
9.7 Overloaded Function for Rectangle Area ........................................................................... 46
9.8 Recursive Power Function.................................................................................................. 47
9.9 Average of Test Scores ....................................................................................................... 47
9.10 Prime Number Check ........................................................................................................ 48
LAB 10: ARRAYS ....................................................................................................................... 49
10.1 Initialize and Print Array Elements ................................................................................... 49
10.2 Store and Display User Inputs in an Array ....................................................................... 49
10.3 Sum and Average of Array Elements ................................................................................ 50
10.4 Find Highest and Lowest in Array .................................................................................... 50
10.5 Array Analysis: Frequency, Above, and Below a Given Number ..................................... 51
10.6 Linear Search in an Array.................................................................................................. 52
10.7 Selection Sort an Array ..................................................................................................... 53
10.8 Count Frequency of Each Element in Array ..................................................................... 53
10.9 Reverse Array Elements .................................................................................................... 54
vi
10.10 Find Duplicate Elements in Array ................................................................................... 55
10.11 Find Unique Elements in Array ....................................................................................... 56
10.12 Student Grades and Averages in Table Format................................................................ 56
10.13 Add Two 3x3 Matrices .................................................................................................... 57
10.14 Add Two 3x3 Matrices .................................................................................................... 58
LAB 12: POINTERS................................................................................................................... 60
12.1 Declare and Use an Integer Pointer ................................................................................... 60
12.2 Increment Value of Variable Using Pointer ....................................................................... 60
12.3 Iterate Through Array with Pointer ................................................................................... 61
12.4 Function to Sum Array Elements Using Pointer ............................................................... 61
12.5 Function to Swap Two Integers Using Pointers ................................................................ 62
12.6 Function to Return Pointer to Maximum Element in Array .............................................. 63
12.7 Sort Array Using Pointer Arithmetic (Bubble Sort) .......................................................... 63
12.8 Dynamically Allocate, Use, and Free Single Integer Memory ......................................... 64
12.9 Dynamically Allocate, Populate, Print, and Free Array Memory ..................................... 65
12.10 Pointer to a Function as an Argument ............................................................................. 65
12.11 C-String to Uppercase Using Pointer Arithmetic ............................................................ 66
12.12 Dynamically Allocated Test Scores: Sort and Average ................................................... 67
12.13 Function to Determine Median of a Sorted Array (Pointer Notation)............................. 68
12.14 Statistical Data for Movies: Average, Median, Mode (Dynamic Allocation) ................. 69
LAB 13: STRUCTURES ............................................................................................................ 71
13.1 Student Structure Declaration and Printing ....................................................................... 71
13.2 Book Structure Initialization and Printing ........................................................................ 71
13.3 Customer Structure Declaration and Initialization (Fixed Values) ................................... 72
13.4 Customer Structure - User Input ....................................................................................... 72
13.5 Customer Structure Array - User Input ............................................................................. 73
13.6 Union for Character and Integer........................................................................................ 75
13. 7 Enumeration with Explicit Values .................................................................................... 75
13.8 Employee Structure Array Iteration .................................................................................. 76
13.9 Car Structure with Pointers and Update Function ............................................................. 77
13.10 Nested Employee Structure ............................................................................................. 78
13.11 Rectangle Structure: Area Calculation and Dimension Update by Reference ................ 78
13.12 Savings Account Structure with Menu ............................................................................ 79
vii
13.13 Company Division Sales Data......................................................................................... 81
13.14 Monthly Budget Tracking ............................................................................................... 83
LAB 14: STRINGS MANIPULATION .................................................................................... 85
14.1 Character to Character Code ............................................................................................. 85
14.2 Print Character Multiple Times ......................................................................................... 85
14.3 Length of Text from Keyboard .......................................................................................... 86
14.4 Compare Two Words Lexicographically ........................................................................... 86
14.5 String Length Using Character Array and Loop ............................................................... 87
14.6 Access and Modify Third Character in String ................................................................... 87
14.7 Reverse String Function (In Place) ................................................................................... 88
14.8 String Length Function (Without strlen) ........................................................................... 88
14.9 Count Vowels and Consonants in String ........................................................................... 89
14.10 Check if String is Palindrome ......................................................................................... 90
14.11 Concatenate Two Strings Function .................................................................................. 91
14.12 Count Words in a Sentence ............................................................................................. 91
14.13 Convert String to Uppercase (Without Built-in) ............................................................. 92
14.14 Function to Count Words in C-String.............................................................................. 92
14.15 Sort 10 Strings Alphabetically (Using Pointers) ............................................................. 93
14.16 Dynamically Allocated 2D String Array with Operations .............................................. 94
14.17 Capitalize First Character of Each Sentence ................................................................... 96
14.18 Password Validation Program ......................................................................................... 97
LAB 15: CLASSES AND OBJECTS ........................................................................................ 98
15.1 Rectangle Class Definition ................................................................................................ 98
15.2 Circle Class with Constructor and Area Calculation ......................................................... 98
15.3 Student Class with Parameterized Constructor ................................................................. 99
15.4 Book Class with Default Constructor and Destructor ..................................................... 100
15.5 Point Class with Copy Constructor ................................................................................. 101
15.6 Employee Class Array with User Input ........................................................................... 102
15.7 Date Class with Three-Parameter Default Constructor and Formats .............................. 103
15.8 Phone Manufacturing Plant Class ................................................................................... 105
LAB 16: INHERITANCE......................................................................................................... 107
16.1 Inheritance: Person and Student Classes ......................................................................... 107
16.2 Polymorphism: Shape, Rectangle, and Circle ................................................................. 107
viii
16.3 Inheritance with Parameterized Constructor (Base Class Call) ...................................... 108
16.4 Protected Members Inheritance ....................................................................................... 109
16.5 Friend Function with Inheritance (Box and ColorBox) ...................................................110
16.6 Inheritance for Account Types (Interest Calculation) ......................................................110
16.7 Abstract Base Class with Pure Virtual Function .............................................................. 111
16.8 Multiple Inheritance: Person, Worker, and Engineer .......................................................112
16.9 Virtual Inheritance: Person, Employee, Student, WorkingStudent ..................................113
16.10 Marks and Result (Composition) ...................................................................................114
16.11 Shape Interface ...............................................................................................................115
16.12 Bank Account Interface ..................................................................................................116
LAB 17: POLYMORPHISM AND ENCAPSULATION........................................................117
17.1 Overload Prefix Increment (++) Operator ........................................................................117
17.2 Overload Addition (+) Operator for Complex Numbers ..................................................117
17.3 Overload Stream Insertion (<<) Operator ........................................................................118
17.4 Function Overloading Example (Area Calculation).........................................................119
17.5 Overload + and - Operators for Complex Numbers .........................................................119
17.6 Virtual Function getRole() with Inheritance ................................................................... 120
17.7 Run-Time Polymorphism with draw() Function ............................................................. 121
17.8 Fuel Efficiency Calculation (Vehicle Hierarchy) ............................................................ 122
17.9 Calculate Salary (Employee Hierarchy) .......................................................................... 123
17.10 Abstract Classes and Pure Virtual Functions (Breathing) ............................................. 124
17.11 Person Class with Getters and Setters ........................................................................... 124
17.12 Most Expensive Book Finder (Using Getters) .............................................................. 125
17.13 Company Class with Static Data Member .................................................................... 126
17.14 BankAccount Class with Read-Only Balance............................................................... 127
17.15 Flight Reservation System Class ................................................................................... 128
LAB 18: TEMPLATES ............................................................................................................. 130
18.1 Template Function findMax() ......................................................................................... 130
18.2 Template Function swapValues() .................................................................................... 130
18.3 Templates for min() and max() Functions ....................................................................... 131
18.4 Template Class Pair ......................................................................................................... 132
18.5 Template Function total() for Running Sum ................................................................... 132
18.6 Template Function printArray() ...................................................................................... 133
ix
18.7 Template Function for Absolute Value ............................................................................ 134
18.8 Template Function sortArray() using Bubble Sort .......................................................... 134
18.9 Template Function findMinMax() for Array ................................................................... 135
18.10 Template Function to Display Array Elements ............................................................. 136
18.11 Template Function for Absolute Value .......................................................................... 137
18.12 Template Function isEqual() with char Specialization.................................................. 137
18.13 Template Function compareThree() .............................................................................. 138
18.14 Template Class Matrix................................................................................................... 139
LAB 19: FILE HANDLING..................................................................................................... 141
19.1 Save Classmate Details to File ........................................................................................ 141
19.2 Read Classmate Information from File ........................................................................... 142
19.3 Count Vowels in a Text File ............................................................................................ 142
19.4 Count Words in a Text File .............................................................................................. 143
19.5 Copy File Content ........................................................................................................... 144
19.6 File Copy Function (without rdbuf()).............................................................................. 144
19.7 Read/Write Array of Integers to Binary File ................................................................... 145
19.8 Display Lines Starting with 'M' or 'N' ............................................................................. 146
19.9 Count Lines in a Text File ............................................................................................... 146
19.10 Copy Integers from Binary File to another Binary File ................................................ 147
19.11 Calculate Average Score from Student Records File .................................................... 148
19.12 Sum and Average from File to File ............................................................................... 149
19.13 Search Word in Text File and Count Occurrences ........................................................ 150
19.14 Write and Read Student Records to/from File .............................................................. 150
19.15 Sort Lines in a File and Write to New File .................................................................... 151
19.16 Check File Existence, Readability, and Writability....................................................... 152
19.17 Open File for Reading with Error Handling.................................................................. 154
19.18 Read CSV File and Print Rows ..................................................................................... 155
19.19 Replace Word in Text File and Save to New File ......................................................... 156
x
LAB
1 LAB 1: INTRODUCTION TO C++ PROGRAMMING
Objective:
Write a C++ program that calculates the sum of two numbers provided by the user.
Steps:
1. Create two variables to hold numbers entered by the user.
2. Prompt the user to input the two numbers.
3. Add the numbers together and store the result in a third variable.
4. Display the result using cout.
Example Input/Output:
Enter the first number: 10
Enter the second number: 20
The sum of the numbers is: 30
Steps:
1. Understand how arithmetic operators work in C++ (+, -, *, /).
2. Create variables for two numbers and take input using cin.
3. Calculate sum, difference, product, and division.
4. Display the sum, difference, product, and division results using cout.
Example Input/Output:
Objective:
Write a C++ program to find the area and perimeter of a rectangle. Note: Accept the length and
width from the user.
Steps:
1. Prompt the user to enter the rectangle's length and width.
2. Use formulas:
o Area = length × width
o Perimeter = 2 × (length + width)
3. Display the results.
Example Input/Output:
Objective:
Write a C++ program to calculate the area of a circle using a constant value for π (PIE).
Steps:
1. Prompt the user to input the circle's radius.
2. Use the formula: Area = π × radius²
3. Define π as a constant: const double PIE = 3.14159;
4. Display the result.
Example Input/Output:
2
1.5 Volume of a Sphere
Objective:
Write a C++ program to compute the volume of a sphere using its radius.
Steps:
1. Prompt the user to input the sphere's radius.
2. Define PI as a constant.
3. Use the formula: Volume = (4/3) × π × radius³
4. Display the result.
5. Hint: Use integer division carefully to avoid precision issues.
Example Input/Output:
Objective:
Write a C++ Program that prompts the user for the distance between two cities and in what speed
you intend to drive. The program should display the time for the trip.
Steps:
1. Prompt the user to input the distance (in km) and speed (in km/h).
2. Use the formula: Time = Distance/Speed
3. Perform the calculation
4. Display the trip time as the results
Example Input/Output:
3
1.7 Weekly Gross Pay
Objective:
Write a C++ program that calculates the weekly gross pay for a worker, based on the total
number of hours worked and the hourly pay rate. Note: Include line comments and block
comments in your program.
Steps:
1. Prompt the user to input hours worked and hourly pay rate.
2. Use the formula: Gross Pay = Hours Worked × Hourly Pay Rate
3. Include line comments and block comments in the code.
Example Input/Output:
Objective:
Write a C++ program to calculate the total amount and VAT for a given unit price and quantity
of items sold. Note: Unit price is VAT exclusive and VAT rate is 16.5%
Steps:
1. Prompt the user to input the unit price and quantity.
2. Calculate the total amount and VAT:
o VAT = Total × 0.165
o Total Amount = Total + VAT
3. Display the results.
Example Input/Output:
4
1.9 Average Monthly Rainfall
Objective:
Write a C ++ program that that calculates the average monthly rainfall for three months
(November, December and January). The program should ask the user to enter the name of each
month, such as January or December, and the amount of rain (in mm) that fell that month.
Steps:
1. Prompt the user to input the name and rainfall (in mm) for three months.
2. Calculate the average rainfall using:
o Average = Total Rainfall / 3
3. Display the result with descriptive output.
4. Hint: Use strings to store month names
Example Input/Output:
5
1.10 Energy Drink Survey
Objective:
K&L soft drink company recently surveyed 12,467 of its customers and found that approximately
14 percent of those surveyed purchase one or more energy drinks per week. Of those customers
who purchase energy drinks, approximately 64 percent of them prefer citrus flavored energy
drinks. Write a C++ program that displays the following:
• The approximate number of customers in the survey who purchase one or more energy
drinks per week.
• The approximate number of customers in the survey who prefer citrus flavored energy
drinks.
Steps:
1. Define constants for the total surveyed customers (12467), percentage of energy drink
consumers (14%), and percentage of citrus-flavored drink preferences (64%).
2. Calculate:
o Customers consuming energy drinks = Total × 14%
o Customers preferring citrus flavor = Energy Drink Consumers × 64%
3. Display the results.
4. Hint: Use integer division carefully to avoid precision issues.
Example Input/Output:
Number of customers who purchase one or more energy drinks per week: 1745
Number of customers who prefer citrus-flavored energy drinks: 1117
6
LAB
2 LAB 2: PROGRAM CONTROL STRUCTURES I
Objective:
Write a program that prompts the user to enter their age. Display "You are eligible to vote." if the
age is 18 or older; otherwise, display nothing.
Steps:
1. Prompt the user to enter their age.
2. Check if the age is 18 or older using an if statement.
3. If the condition is met, display the message "You are eligible to vote."
4. If the condition is not met, do not display any message.
Example Input/Output:
Enter your age: 20
You are eligible to vote.
Objective:
Write a C++ program to determine whether a given integer is even or odd.
Steps:
1. Prompt the user to enter an integer.
2. Use the modulus operator (%) to check if the number is divisible by 2.
3. If the remainder is 0, display "The number is even."
4. Otherwise, display "The number is odd."
Example Input/Output:
Enter an integer: 7
The number is odd.
7
Enter an integer: 14
The number is even.
Objective:
Develop a C++ program to check whether a given year is a leap year or not.
Steps:
1. Prompt the user to enter a year.
2. A year is a leap year if:
o It is divisible by 4 but not divisible by 100, or
o It is divisible by 400.
3. Use an if-else statement to implement the conditions.
4. Display whether the year is a leap year or not.
Example Input/Output:
Enter a year: 2020
2020 is a leap year.
Objective:
Write a C++ program that takes a grade input and outputs "FAIL" if the grade is between 0 to 49,
"PASS" for 50 to 59, "CREDIT" for 60 to 74, "DISTINCTION" for 75 to 100; otherwise, it should
display "INVALID GRADE ENTERED".
Steps:
1. Prompt the user to enter a grade.
2. Use if-else statements to classify the grade:
o 0-49: "FAIL"
o 50-59: "PASS"
o 60-74: "CREDIT"
o 75-100: "DISTINCTION"
3. Display "INVALID GRADE ENTERED" if the grade is outside the 0-100 range.
8
Example Input/Output:
Enter a grade: 65
CREDIT
Objective:
Write a C++ program that prompts the user to input two numbers. Determine and display
whether the first number is greater than, less than, or equal to the second number.
Steps:
1. Prompt the user to enter two numbers.
2. Use if-else statements to compare the numbers:
o Display "The first number is greater than the second."
o Display "The first number is less than the second."
o Display "The numbers are equal."
Example Input/Output:
9
Steps:
1. Prompt the user to enter their age.
2. Use if-else statements to determine the ticket price:
o Age 0-12: MK1000
o Age 13-64: MK1500
o Age 65 and above: MK1200
3. Display the ticket price.
Example Input/Output:
Enter your age: 8
Your ticket price is MK1000.
Objective:
Write a C++ program that asks the user to input the lengths of three sides of a triangle. Classify
and print the type of the triangle based on the lengths entered:
a. Equilateral: All sides are equal.
b. Isosceles: Two sides are equal.
c. Scalene: No sides are equal.
Steps:
1. Prompt the user to enter the lengths of the three sides of a triangle.
2. Use if-else statements to classify the triangle:
o Equilateral: All three sides are equal.
o Isosceles: Two sides are equal.
o Scalene: All sides are different.
3. Display the type of triangle.
Example Input/Output:
Enter the length of the first side: 5
4.
Enter
5. the length of the second side: 5
Enter the length of the third side: 8
The triangle is Isosceles.
10
LAB
3 LAB 3: PROGRAM CONTROL STRUCTURES II
Objective:
Write a C++ program that takes two integers and an arithmetic operator (+, -, *, /) as input, then
performs the corresponding operation using a switch statement and displays the result.
Steps:
1. Prompt the user to enter two integers and an arithmetic operator (+, -, *, /).
2. Use a switch statement to determine which operation to perform.
3. Ensure division by zero is handled correctly.
4. Display the result of the operation.
Example Input/Output:
Enter the first number: 10
Enter the second number: 5
Enter the operator (+, -, *, /): *
Result: 10 * 5 = 50
Objective:
Write a C++ program that asks the user to enter a number within the range of 1 through 5 and
displays the Roman numeral version of that number using a switch statement.
Steps:
1. Prompt the user to enter a number between 1 and 5.
2. Use a switch statement to map numbers to Roman numerals.
3. If the user enters a number outside the valid range, display an error message.
Example Input/Output:
Enter a number between 1 and 5: 3
The Roman numeral version is: III
11
Example Invalid Input:
Steps:
1. Prompt the user to input a color ('R' for red, 'Y' for yellow, 'G' for green).
2. Use a switch statement to display the appropriate message.
o 'R': "Stop!"
o 'Y': "Prepare to stop."
o 'G': "Go ahead."
3. Handle invalid inputs with an error message.
Example Input/Output:
12
3.4 Geometry Calculator
Objective:
Write a C++ program that displays the following menu:
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit
Enter your choice (1-4):
If the user enters 1, the program should ask for the radius of the circle and then display its area.
Use 3.14159 for π. If the user enters 2, the program should ask for the length and width of the
rectangle, and then display the rectangle’s area. If the user enters 3, the program should ask for the
length of the triangle’s base and its height, and then display its area. If the user enters 4, the
program should end.
Input Validation: Display an error message if the user enters a number outside the range of 1
through 4 when selecting an item from the menu. Do not accept negative values for the circle’s
radius, the rectangle’s length or width, or the triangle’s base or height
Steps:
1. Display the following menu:
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit
Enter your choice (1-4):
13
Example Input/Output:
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit
Enter your choice (1-4): 1
Enter the radius of the circle: 5
The area of the circle is: 78.54
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit
Enter your choice (1-4): 5
Error: Please enter a number between 1 and 4.
14
LAB
4 LAB 4: PROGRAM CONTROL STRUCTURES III
Objective:
Write a C++ program to display all odd numbers between 0 and 100.
Steps:
1. Use a loop to iterate through numbers from 1 to 100.
2. Use an if statement to check if the number is odd (number % 2 != 0).
3. Display the odd numbers.
Example Output:
1 3 5 7 9 ... 99
Objective:
Write a C++ program to display the numbers 1 to 5 along with their squares.
Steps:
1. Use a loop to iterate through numbers 1 to 5.
2. Calculate the square of each number (square = number * number).
3. Display the number and its square in tabular form.
Example Output:
Number Square
1 1
2 4
3 9
4 16
5 25
15
4.3 Modify Program to Allow User Input for Range
Objective:
Modify the above program (4.2) to allow the user to specify how many numbers to display along
with their squares.
Steps:
1. Prompt the user to enter the number of values to display.
2. Use a loop to iterate through the specified range, calculating and displaying each number
and its square.
Example Input/Output:
Objective:
Use a for loop to display numbers from 0 to 1000 in increments of 10.
Steps:
1. Use a for loop starting at 0 and ending at 1000.
2. Increment the loop variable by 10.
3. Display the numbers.
Example Output:
0 10 20 30 ... 1000
16
4.5 Display Numbers from 0 to 1000 in Steps of 10
Objective:
Write a C++ program that uses a while loop to display numbers starting from 0 and increasing
by 10 until the value reaches 1000.
Steps:
1. Initialize a variable to 0.
2. Use a while loop to:
a. Display the current value.
b. Increase the value by 10.
3. Continue the loop until the value reaches 1000.
Example Input/Output:
0 10 20 30 ... 1000
Objective:
Write a program where the user enters a number, which is then multiplied by 2 until it exceeds
50. Use a while loop.
Steps:
1. Prompt the user to enter a number.
2. Use a while loop to multiply the number by 2 and display it.
3. Stop when the number exceeds 50.
Example Input/Output:
Enter a number: 5
5
10
20
40
80
17
4.7 Sum of All Even Numbers Between 1 and 100
Objective:
Develop a C++ program to find the sum of all even numbers between 1 and 100 using a for
loop.
Steps:
1. Use a for loop to iterate through numbers from 1 to 100.
2. Check if the number is even (number % 2 == 0).
3. Add even numbers to a sum variable and display the total.
Example Output:
The sum of all even numbers between 1 and 100 is: 2550
Objective:
Develop a C++ program to find the sum of digits of a given number using a do-while loop.
Steps:
1. Prompt the user to enter a number.
2. Use a do-while loop to extract digits (digit = number % 10) and add them to a sum
variable.
3. Divide the number by 10 in each iteration to remove the last digit.
4. Display the sum.
Example Input/Output:
Enter a number: 123
The sum of digits is: 6
18
4.9 Factorial Using a For Loop
Objective:
Write a C++ program to calculate the factorial of a given number using a for loop.
Steps:
1. Prompt the user to enter a non-negative number.
2. Use a for loop to calculate the factorial (factorial *= i).
3. Display the result.
Example Input/Output:
Enter a number: 5
The factorial of 5 is: 120
Objective:
Write a C++ program to reverse a given number using a while loop.
Steps:
1. Prompt the user to enter a number.
2. Use a while loop to extract digits (digit = number % 10) and form the reversed
number (reversed = reversed * 10 + digit).
3. Display the reversed number.
Example Input/Output:
19
4.11 Sum of All Prime Numbers Between 1 and 100
Objective:
Write a C++ program to calculate the sum of all prime numbers between 1 and 100 using a
while loop.
Steps:
1. Start with the first prime number, which is 2.
2. Use a while loop to iterate through numbers from 2 to 100.
3. For each number, check if it is a prime number using a nested loop. A prime number is
only divisible by 1 and itself.
4. If a number is prime, add it to a running sum.
5. Display the total sum of all prime numbers between 1 and 100.
Example Output:
The sum of all prime numbers between 1 and 100 is: 1060
20
LAB
5 LAB 5: PROGRAM CONTROL STRUCTURES IV
Objective:
Write a C++ program that asks the user for a positive integer value. The program should use a
loop to get the sum of all the integers from 1 up to the number entered.
For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, … 50.
Steps:
1. Prompt the user to enter a positive integer.
2. Use a loop to calculate the sum of all integers from 1 to the entered value.
3. Display the result.
Example Input/Output:
Objective:
Assuming the level of the Lake Malawi continues rising at about 3.1 millimeters per year, write a
C++ program that displays a table showing the total number of millimeters the lake will have risen
each year for the next 25 years.
Steps:
1. Initialize the annual rise as 3.1 mm.
2. Use a loop to calculate the total rise for each year.
3. Display the year and cumulative rise in a tabular format.
Example Input/Output:
21
5.3 Doubling Salary Table
Objective:
Write a C++ program that calculates how much a person earns in a month if the salary is 10 tambala
the first day, 20 tambala the second day, 40 tambala the third day, and so on with the daily pay
doubling each day the employee works.
The program should ask the user for the number of days the employee worked during the month
and should display a table showing how much the salary was for each day worked, as well as the
total pay earned for the month.
Note: The output should be displayed in Kwachas with two decimal points, not in Tambala
Steps:
1. Ask the user for the number of days worked.
2. Use a loop to calculate and display daily pay and cumulative pay in Kwachas. Convert
Tambala to Kwachas (1 Kwacha=100 Tambala1).
3. Format the output to two decimal places.
Example Input/Output:
22
5.4 Vehicle Distance Traveled
Objective:
The distance a vehicle travels can be calculated as follows:
distance = speed * time
For example, if a car travels 40 km per hour for 3 hours, the distance traveled is 120 km. Write a
C++ program that asks the user for the speed of a vehicle (in km per hour) and how many hours
it has traveled. The program should display the total distance traveled at the end of each hour of
that time period.
Input Validation: Do not accept a negative number for speed and do not accept any value less
than one for time traveled.
The sample output: (if the speed of the of the car is 40 km/h, and the hours traveled is 3 hrs.)
Steps:
1. Ask the user for the speed (km/h) and time (hours).
2. Validate that speed is non-negative and time is at least 1.
3. Use a loop to calculate and display the distance for each hour.
Example Input/Output:
23
5.5 Compound Interest Calculation
Objective:
Write a C++ program that takes in capital, interest rate and period (number of years) and then
calculates the compound interest for each year using the following formulae:
The program should display the Year, Interest and Yearly Capital. A sample output is given
below: (If capital is 30000.00, interest 12.5% and period is 3 years, the output is as below)
Steps:
1. Ask the user for the initial capital, interest rate, and period (in years).
2. Use a loop to calculate yearly interest and updated capital.
3. Display the results in a tabular format.
Example Input/Output:
24
5.6 Factorial Calculation Without Predefined Functions
Objective:
Write a C++ program to calculate the factorial of a given integer entered by the user, without
utilizing any pre-defined functions. Note: Ensure that negative numbers are not entered, as factorial
is not defined for negative integers.
Steps:
1. Prompt the user for a non-negative integer. Validate that the input is non-negative.
2. Use a loop to calculate the factorial.
3. Display the result.
Example Input/Output:
DAILY SALES
(each * = K 100)
Store 1: **********
Store 2: ************
Store 3: *********
Input Validation: Do not accept sales figures less than K0.00.
Steps:
1. Prompt the user for the sales figures for three stores. Validate that sales are non-negative.
2. Use a loop to generate asterisks for each store's sales.
3. Display the bar graph.
25
Example Input/Output:
DAILY SALES
(each * = K100)
Store 1: **********
Store 2: ************
Store 3: *********
26
LAB
6 LAB 6: FUNCTIONS I
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Prompt the user to input a non-negative number.
3. Use the sqrt() function to calculate the square root of the number.
4. Display the result in a clear and formatted manner.
5. Handle invalid input (e.g., negative numbers) by displaying an appropriate error message.
Example Input/Output:
Objective:
Write a C++ program to calculate and display the power of a given base raised to an exponent
using the pow() function from the <cmath> library.
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Ask the user to input a base and an exponent (both can be floating-point values).
3. Use the pow() function to calculate the result of raising the base to the exponent.
4. Display the result in a clear and formatted manner.
27
Example Input/Output:
Enter the base: 2
Enter the exponent: 3
Result: 8
Objective:
Write a C++ program to round a floating-point number to the nearest integer using the round()
function from the <cmath> library.
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Prompt the user to input a floating-point number.
3. Use the round() function to round the number to the nearest integer.
4. Display the result in a clear and formatted manner.
Example Input/Output:
28
6.4 Calculating Logarithms
Objective:
Write a C++ program that uses the cmath library to calculate and display the natural logarithm
and logarithm base 10 of a user-provided number.
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Ask the user to input a positive number.
3. Use the log() function from the cmath library to calculate the natural logarithm
(base e) of the input number.
4. Use the log10() function from the cmath library to calculate the base-10 logarithm
of the input number.
5. Handle invalid input (e.g., non-positive numbers) by displaying an appropriate error
message.
6. Display the results to the user in a clear and formatted manner.
Example Input/Output:
Enter a positive number: 100
Natural Logarithm (ln): 4.60517
Base-10 Logarithm (log10): 2
Objective:
Write a C++ program to convert a user-provided lowercase letter to uppercase using the
toupper() function from the <cctype> library.
Steps:
1. Include the <iostream> and <cctype> libraries in your program.
2. Prompt the user to input a single lowercase letter.
3. Use the toupper() function to convert the letter to uppercase.
4. Display the uppercase letter.
5. Handle invalid input (e.g., non-lowercase characters) by displaying an error message.
Example Input/Output:
Enter a lowercase letter: a
Uppercase: A
29
Example Invalid Input:
Objective:
Write a C++ program to calculate and display the absolute value of a user-provided number
using the fabs() function from the <cmath> library.
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Prompt the user to input a floating-point or integer value.
3. Use the fabs() function to calculate the absolute value of the number.
4. Display the result in a clear and formatted manner.
Example Input/Output:
Objective:
Write a C++ program to check whether a given character is a digit using the isdigit() function
from the <cctype> library.
Steps:
1. Include the <iostream> and <cctype> libraries in your program.
2. Prompt the user to input a single character.
3. Use the isdigit() function to check if the character is a digit.
4. Display whether the character is a digit or not.
Example Input/Output:
Enter a character: 5
The character is a digit.
30
Example Invalid Input:
Enter a character: a
The character is not a digit.
Objective:
Write a C++ program to calculate and display the sine, cosine, and tangent of an angle (in
radians) entered by the user using the <cmath> library.
Steps:
1. Include the <iostream> and <cmath> libraries in your program.
2. Prompt the user to input an angle in radians.
3. Use the sin(), cos(), and tan() functions to calculate the trigonometric values.
4. Display the results in a clear and formatted manner.
Example Input/Output:
31
6.9 Generate and Print Five Random Numbers
Objective:
Write a C++ program to generate and display five random numbers between 1 and 100 using the
<cstdlib> and <iostream> libraries.
Steps:
1. Include the <iostream> and <cstdlib> libraries.
2. Seed the random number generator using srand() and the current time.
3. Use rand() to generate five random numbers in the range of 1 to 100.
4. Display the generated numbers in a clear and formatted manner.
Example Output:
Objective:
Write a C++ program that generates a random number between 1 and 5, prompts the user to
input a number, and provides feedback on whether the user’s guess is less than, greater than, or
equal to the generated number.
Steps:
1. Include the <ctime>, <cstdlib>, and <iostream> libraries.
2. Seed the random number generator using srand() and the current time.
3. Generate a random number between 1 and 5 using rand().
4. Prompt the user to input a number between 1 and 5.
5. Compare the user’s input with the generated number and display whether the guess is too
low, too high, or correct.
Example Input/Output:
32
LAB
7 LAB 7: FUNCTIONS II
Objective:
Write a C++ program that defines a function named add to calculate the sum of two integers. The
function should be defined outside the main() function and called inside main() to demonstrate
its functionality.
Steps:
1. Define a function add that takes two integers as parameters and returns their sum.
2. Inside the main() function, prompt the user to input two integers.
3. Call the add function with the user inputs and display the result.
Example Input/Output:
Objective:
Write a C++ program to calculate the area of a circle using a function called calculateArea().
Steps:
1. Define a function calculateArea that takes the radius of a circle as a parameter and
returns its area (use the formula: area = π * radius²).
2. Inside the main() function, prompt the user to input the radius of the circle.
3. Call the calculateArea function and display the result. Use the value 3.14159 for π.
Example Input/Output:
33
7.3 Calculate the Cube of a Number
Objective:
Write a C++ program that defines a function named cube to calculate the cube of an integer.
Steps:
1. Define a function cube that takes an integer as a parameter and returns its cube.
2. Inside the main() function, prompt the user to input an integer.
3. Call the cube function and display the result.
Example Input/Output:
Enter a number: 3
The cube of the number is: 27
Objective:
Write a C++ program to find the maximum of two integers using a function named findMax().
Steps:
1. Define a function findMax that takes two integers as parameters and returns the larger of
the two.
2. Inside the main() function, prompt the user to input two integers.
3. Call the findMax function and display the result.
Example Input/Output:
34
7.5 Check if a Number is Even
Objective:
Write a C++ program that defines a function named isEven to determine whether a number is
even.
Steps:
1. Define a function isEven that takes an integer as a parameter and returns true if the
number is even, and false otherwise.
2. Inside the main() function, prompt the user to input an integer.
3. Call the isEven function and display the result.
Example Input/Output:
Enter a number: 8
The number is even.
Objective:
Write a C++ program to calculate the factorial of a number using a function named factorial().
Steps:
1. Define a function factorial that takes an integer as a parameter and returns its factorial.
2. Inside the main() function, prompt the user to input an integer.
3. Call the factorial function and display the result.
Example Input/Output:
Enter a number: 5
The factorial is: 120
35
7.7 Calculate Power Using a Function
Objective:
Write a C++ program to calculate the power of a number using a function named power().
Steps:
1. Define a function power that takes two integers, base and exponent, as parameters and
returns the result of raising the base to the exponent.
2. Inside the main() function, prompt the user to input a base and an exponent.
3. Call the power function and display the result.
Example Input/Output:
Enter the base: 2
Enter the exponent: 3
The result is: 8
Objective:
Write a C++ program that includes two functions: addition() and multiplication().The
addition() function should take two integer parameters and return their sum, while the
multiplication() function should take two integer parameters and return their product. In the
main() function, ask the user to enter two integers and then call both functions to display their
sum and product.
Steps:
1. Define a function addition that takes two integers as parameters and returns their sum.
2. Define another function multiplication that takes two integers as parameters and
returns their product.
3. Inside the main() function, prompt the user to input two integers.
4. Call both functions and display the results.
Example Input/Output:
36
7.9 Maximum, Minimum, and Average of Three Numbers
Objective:
Write a C++ program that includes three functions: maximum(), minimum(), and average().The
maximum() function should take three integer parameters and return the largest among them, the
minimum() function should take three integer parameters and return the smallest among them, and
the average() function should take three integer parameters and return their average. In the
main() function, ask the user to input three integers, and then call these functions to display the
maximum, minimum, and average.
Steps:
1. Define a function maximum that takes three integers as parameters and returns the largest
among them.
2. Define a function minimum that takes three integers as parameters and returns the smallest
among them.
3. Define a function average that takes three integers as parameters and returns their
average.
4. Inside the main() function, prompt the user to input three integers.
5. Call all three functions and display the results.
Example Input/Output:
37
LAB
8 LAB 8: FUNCTIONS III
Objective:
Write a C++ program that uses an inline function named circleArea() to calculate the area of a
circle.
Steps:
1. Define an inline function circleArea() that accepts the radius as a parameter and
returns the area of the circle using the formula: Area=π*radius2. Use π=3.14159
2. Inside the main() function, prompt the user to input the radius.
3. Call the circleArea() function and display the result.
Example Input/Output:
Enter the radius of the circle: 5
The area of the circle is: 78.53975
Objective:
Write a C++ program with a recursive function that calculates the sum of integers from n down
to 1.
Steps:
1. Define a recursive function sumToOne() that accepts an integer n as a parameter.
o If n is 1, return 1.
o Otherwise, return n+sumToOne(n−1)
2. Inside the main() function, prompt the user to input a positive integer.
3. Call the sumToOne() function and display the result.
Example Input/Output:
Enter a positive integer: 5
The sum of integers from 5 to 1 is: 15
38
8.3 Iterative Function to Sum Integers
Objective:
Implement the same functionality as above program (8.2) using an iterative approach.
Steps:
1. Define a function sumToOneIterative() that accepts an integer n and calculates the sum
using a loop.
2. Inside the main() function, prompt the user to input a positive integer.
3. Call the sumToOneIterative() function and display the result.
Example Input/Output:
Enter a positive integer: 5
The sum of integers from 5 to 1 is: 15
Objective:
Write a C++ program that includes the two specified alternate functions. Each function is designed
to triple an integer provided by the user within the main() function. The two functions are as
follows:
a. tripleByValue() function: It accepts a copy of the integer by value, triples the
copied value, and returns the new tripled value.
b. tripleByReference() function: It accepts the integer by reference using a
reference parameter, enabling direct modification of the original integer value by
tripling it through its alias (i.e., the reference parameter).
Your task is to implement these functions and demonstrate their usage within the main program by
accepting an integer from the user and displaying the results of both function calls.
Steps:
1. Define both functions with appropriate logic.
2. Inside the main() function, prompt the user to input an integer.
3. Call both functions and display the results.
Example Input/Output:
Enter an integer: 4
Triple by value: 12
Triple by reference: 12
39
8.5 Overloaded Functions for Shape Area Calculation
Objective:
Write a C++ program that employs overloaded functions named calculateArea(). These
functions are designed to determine the area of different shapes: a rectangle (specified by its length
and width), a circle (specified by its radius), and a triangle (specified by its base and height). In
the main() function, the user is prompted to input the required values for each shape, and then
the respective calculateArea() functions are called to compute and display the areas.
Steps:
1. Define three versions of calculateArea():
o Rectangle: Accepts length and width.
o Circle: Accepts radius.
o Triangle: Accepts base and height.
2. Inside the main() function, prompt the user for inputs for each shape and call the
respective function.
Example Input/Output:
40
8.6 Recursive Factorial Function
Objective:
Write a C++ program with a recursive function to compute the factorial of a non-negative integer.
Within the main()function, prompt the user to enter a non-negative integer. If the input is
negative, display a message indicating that factorial calculation is not applicable for negative
numbers. Otherwise, invoke the factorial function with the provided number and print the resulting
factorial value.
Steps:
1. Define a recursive function factorial():
o If n is 0 or 1, return 1.
o Otherwise, return n*factorial(n−1).
2. Inside the main() function, prompt the user to input a non-negative integer.
3. Validate the input and call the factorial() function if valid.
Example Input/Output:
Enter a non-negative integer: 5
The factorial is: 120
Objective:
Write a C++ Program that implement a recursive function to find the n-th Fibonacci number. The
main() function takes user input for the value of n and then calls the fibonacci() function to
compute and display the nth Fibonacci number.
Note: assume that the Fibonacci sequence starts with 0 as the 0th Fibonacci number and 1 as the
1st Fibonacci number.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding
ones, usually starting with 0 and 1. So the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Steps:
1. Define a recursive function fibonacci():
o If n is 0, return 0.
o If n is 1, return 1.
o Otherwise, return fibonacci(n−1)+fibonacci(n−2)
2. Inside the main() function, prompt the user to input an integer n.
3. Call the fibonacci() function and display the result.
41
Example Input/Output:
Objective:
Write a C++ program that implements a recursive function to compute the greatest common divisor
(GCD) of two positive integers using Euclid's algorithm. The main()function should request the
user to input two positive integers, validate the input, and subsequently determine and display their
GCD using the gcd() function.
Steps:
1. Define a recursive function gcd():
o If b is 0, return a.
o Otherwise, return gcd(b,a%b).
2. Inside the main() function, prompt the user to input two positive integers.
3. Validate the inputs and call the gcd() function if valid.
Example Input/Output:
42
LAB
9 LAB 9: FUNCTIONS IV
Objective:
Write a C++ program that demonstrates the use of header files by creating a separate header file
"functions.h" that contains the prototypes for basic arithmetic functions like addition,
subtraction, multiplication, and division. Include this header file in your main program to perform
these operations on two numbers entered by the user.
Steps:
1. Create a header file function.h that declares functions for arithmetic operations.
2. Write the implementation of these functions in the main program.
3. Prompt the user for two numbers and display the results of all operations.
Example Input/Output:
Objective:
Create a C++ program that makes use of a custom header file named "utilities.h" This
header file includes functions such as finding the maximum and minimum of two numbers and
calculating the square root of a number [Maximum or Minimum returned]. Implement these
functions within your main program and showcase their functionality by taking input from the
user.
Steps:
1. Create utilities.h to declare prototypes for findMax, findMin, and calculateSqrt
functions.
2. Write the implementation of these functions in the main program.
3. Prompt the user for two numbers and demonstrate functionality.
43
Example Input/Output:
Enter two numbers: 25 16
Maximum: 25
Minimum: 16
Square root of the maximum: 5
Example Input/Output:
Enter length and width: 8 4
The perimeter of the rectangle is: 24
Objective:
Write a C++ program to calculate the factorial of a number using a header file "factorial.h"
that declares a function for factorial calculation. Implement the factorial function in a separate
source file "[Link]" and include the header file in the main program to compute
factorial values.
Steps:
1. Create factorial.h to declare the factorial(int n) function.
2. Implement the function in [Link] using recursion.
3. Include the header file in the main program to compute factorial values.
44
Example Input/Output:
Enter a number: 5
The factorial of 5 is: 120
Objective:
Develop a header file "math_operations.h" that includes functions for finding the square
root and absolute value of a number. Implement these functions in "math_operations.cpp"
and demonstrate their usage [accepting the number from the user] in the main program by
including the header file
Steps:
1. Declare calculateSqrt(double number) and calculateAbs(double number) in
math_operations.h.
2. Implement the functions in math_operations.cpp.
3. Use these functions in the main program to compute results for user input.
Example Input/Output:
Enter a number: -25
Square root: 5
Absolute value: 25
Objective:
Create a header file "calculator.h" that declares functions for performing basic calculator
operations such as addition, subtraction, multiplication, and division. Implement these functions
in a C++ file "[Link]" and build a calculator program that takes operator input (+, -
, *, /) and two operands from the user to perform the desired operation.
Steps:
1. Declare calculator functions (add, subtract, multiply, divide) in calculator.h.
2. Implement these in [Link].
3. Create a main program to prompt the user for an operator and two operands, and perform
the desired operation.
45
Example Input/Output:
Enter operator (+, -, *, /): +
Enter two numbers: 7 3
Result: 10
Objective:
Create two versions of a function called calculateRectArea that returns the area of a
rectangle: one that takes two integers length and width and one that takes two doubles length and
width. Declare global variables intRectArea and doubleRectArea to store the results of
calling each version of the function, respectively.
Write a C++ program that calculates and stores the areas of rectangles with different dimensions
using both versions of the function, and then prints the results.
Steps:
1. Define overloaded calculateRectArea(int, int) and calculateRectArea(double,
double) functions.
2. Use global variables intRectArea and doubleRectArea to store the results.
3. Calculate and print the areas for user input.
Example Input/Output:
46
9.8 Recursive Power Function
Objective:
Write a recursive function called calculatePower that takes two integers base and exponent
and calculates base raised to the power of exponent. Use local variables within the function to store
intermediate results during recursion.
Write a C++ program to input values for base and exponent, call the calculatePower
function, and print the result.
Steps:
1. Define calculatePower(int base, int exponent):
o If exponent is 0, return 1.
o Otherwise, return base*calculatePower(base, exponent-1)
2. Prompt the user for base and exponent
3. Display the result.
Example Input/Output:
Enter base and exponent: 2 3
Result: 8
Input Validation: Do not accept test scores lower than 0 or higher than 100.
47
Steps:
1. Define void getScore(int &score) to validate scores (0 to 100).
2. Define int findLowest() to find the lowest score.
3. Define void calcAverage() to compute the average of the top four scores.
4. Prompt the user for five scores and display the average.
Example Input/Output:
Enter score 1: 80
Enter score 2: 95
Enter score 3: 88
Enter score 4: 70
Enter score 5: 92
The average of the top four scores is: 88.75
Objective:
A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. For
example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6,
however, is not prime because it can be divided by 1, 2, 3, and 6.
Write a Boolean function named isPrime(), which takes an integer as an argument and returns
true if the argument is a prime number, and false otherwise. Demonstrate the function in a complete
program.
Steps:
1. Define isPrime(int number):
o Return false if number ≤ 1
o Check divisors from 2 to √number. If any divisor evenly divides the number,
return false.
o Otherwise, return true.
2. Prompt the user for a number and display the result.
48
LAB
10 LAB 10: ARRAYS
Objective:
Write a C++ program to initialize an array of 10 integers with values from 1 to 10 and print the
array elements.
Steps:
1. Declare an integer array of size 10.
2. Use a loop to assign values from 1 to 10 to each element of the array.
3. Use another loop to print each element of the array.
Example Input/Output:
Array elements: 1 2 3 4 5 6 7 8 9 10
Objective:
Write a C++ program to take 5 integer inputs from the user, store them in an array, and then
display the elements of the array.
Steps:
1. Declare an integer array of size 5.
2. Use a loop to prompt the user to enter 5 integers and store each input in the array.
3. Use another loop to print each element of the array.
Example Input/Output:
Enter 5 integers:10 20 30 40 50
Array elements: 10 20 30 40 50
49
10.3 Sum and Average of Array Elements
Objective:
Write a C++ program that asks the user to enter 12 integers, stores them in an array, and then
calculates and prints the sum and average of the array elements.
Steps:
1. Declare an integer array of size 12.
2. Initialize a variable for sum to 0.
3. Use a loop to prompt the user to enter 12 integers and store them in the array, adding each
to the sum.
4. Calculate the average by dividing the sum by the number of elements (12.0 for floating-
point division).
5. Print the calculated sum.
6. Print the calculated average.
Example Input/Output:
Enter 12 integers:1 2 3 4 5 6 7 8 9 10 11 12
Sum: 78
Average: 6.5
Objective:
Write a C++ program that prompts the user to enter 10 integers, stores them in an array, and then
finds and displays both the highest and lowest integers in the array.
Steps:
1. Declare an integer array of size 10.
2. Use a loop to prompt the user to enter 10 integers and store them in the array.
3. Initialize variables for highest and lowest with the first element of the array.
4. Use a loop to iterate through the rest of the array elements:
a. If an element is greater than highest, update highest.
b. If an element is less than lowest, update lowest.
5. Print the highest integer found.
6. Print the lowest integer found.
50
Example Input/Output:
Enter 10 integers: 15 8 23 4 30 12 6 19 2 27
Highest: 30
Lowest: 2
Objective:
Write a C++ program that asks the user to enter 10 integers, stores them in an array, and then finds
how many times a given number appears in the array, finds and displays all values from the array
that are above a given number, and finds and displays all values from the array that are below a
given number.
Steps:
1. Declare an integer array of size 10.
2. Use a loop to prompt the user to enter 10 integers and store them in the array.
3. Prompt the user to enter a "given number" for comparison.
4. For frequency:
a. Initialize a count variable to 0.
b. Iterate through the array and if an element equals the "given number",
increment count.
c. Print the frequency of the "given number".
5. For numbers above the given number:
a. Print a header "Numbers above [given number]:".
b. Iterate through the array and if an element is greater than the "given number",
print the element.
6. For numbers below the given number:
a. Print a header "Numbers below [given number]:".
b. Iterate through the array and if an element is less than the "given number",
print the element.
Example Input/Output:
Enter 10 integers:5 10 3 10 7 12 1 10 8 6
Enter a number to compare: 10
51
10.6 Linear Search in an Array
Objective:
Write a C++ program that asks the user to enter the number of elements in an array, the elements
of the array, and a value to search for. Implement a linear search to find the value and return the
index if found, or a message if not found.
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Prompt the user to enter the value to search for.
5. Initialize a variable foundIndex to -1 (to indicate not found).
6. Use a loop to iterate through the array from the first element to the last:
a. If the current element matches the value to search for, set foundIndex to the
current index and break the loop.
7. If foundIndex is not -1, print a message indicating the value was found at foundIndex.
8. Else (if foundIndex is -1), print a message indicating the value was not found.
Example Input/Output:
52
10.7 Selection Sort an Array
Objective:
Write a C++ program that asks the user to enter the number of elements in an array and the elements
of the array. Implement the selection sort algorithm to sort the array in ascending order and print
the sorted array.
Clarification:
Selection sort works by repeatedly finding the minimum element from the unsorted part of the
array and putting it at the beginning of the unsorted part.
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Implement the selection sort algorithm:
a. Loop from i = 0 to n-2 (outer loop).
b. Inside the outer loop, assume array[i] is the minimum, store its index as
minIndex = i.
c. Loop from j = i+1 to n-1 (inner loop).
d. If array[j] is less than array[minIndex], update minIndex = j.
e. After the inner loop, if minIndex is not equal to i, swap array[i] and
array[minIndex].
5. Print the sorted array.
Example Input/Output:
Sorted array: 11 12 22 25 64
Objective:
Write a C++ program that asks the user to enter the number of elements in an array and the
elements of the array. Count the frequency of each element in the array and print the frequency
count.
53
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Declare a boolean array, say visited, of the same size n, initialized to false. This is to
keep track of elements whose frequencies have already been counted.
5. Use a nested loop to count frequencies:
a. Outer loop: Iterate from i = 0 to n-1.
b. If visited[i] is true, continue to the next iteration (skip already counted
elements).
c. Initialize count = 1.
d. Inner loop: Iterate from j = i+1 to n-1.
e. If array[i] is equal to array[j], increment count and set visited[j] =
true.
f. After the inner loop, print array[i] and its count.
Example Input/Output:
Objective:
Write a C++ program that asks the user to enter the number of elements in an array and the
elements of the array. Reverse the elements of the array and print the reversed array.
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Reverse the array:
a. Use a loop that iterates from i = 0 up to n/2 - 1.
b. In each iteration, swap array[i] with array[n - 1 - i]. (A temporary
variable will be needed for swapping).
5. Print the reversed array.
54
Example Input/Output:
Enter the number of elements: 5
Enter elements:1 2 3 4 5
Reversed array: 5 4 3 2 1
Objective:
Write a C++ program that asks the user to enter the number of elements in an array and the
elements of the array. Find and print all duplicate elements in the array.
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Print a header "Duplicate elements:".
5. Use a nested loop to find duplicates:
a. Outer loop: Iterate from i = 0 to n-2.
b. Inner loop: Iterate from j = i+1 to n-1.
c. If array[i] is equal to array[j], and array[i] has not been printed as a
duplicate before (you might need a way to track printed duplicates, or just print
them as they are found, which might result in repeated duplicate output if an
element appears more than twice), print array[i]. A simple way to avoid
repeated printing for the same duplicate value is to mark it or use a separate
temporary array to store found duplicates and check against it. For simplicity, just
print them as found.
Example Input/Output:
Duplicate elements: 10 20 10
55
10.11 Find Unique Elements in Array
Objective:
Write a C++ program that asks the user to enter the number of elements in an array and the
elements of the array. Find and print all unique elements in the array.
Steps:
1. Prompt the user to enter the number of elements (let's call it n).
2. Declare an integer array of size n.
3. Use a loop to prompt the user to enter n integer elements and store them in the array.
4. Print a header "Unique elements:".
5. Use a nested loop to find unique elements:
a. Outer loop: Iterate from i = 0 to n-1.
b. Initialize a boolean isUnique = true.
c. Inner loop: Iterate from j = 0 to n-1.
d. If i is not equal to j AND array[i] is equal to array[j], set isUnique =
false and break the inner loop.
e. After the inner loop, if isUnique is true, print array[i].
Example Input/Output:
Unique elements: 30 40
Objective:
Write a C++ program that accepts 6 grades for each of 5 students. The program should calculate
the average for each student and display the grades and averages in a table format. Additionally,
the program should display the highest and lowest averages.
Clarification:
You will need a 2D array to store the grades (e.g., grades[5][6]).
Steps:
1. Define constants for number of students (5) and number of grades (6).
2. Declare a 2D integer array, grades[5][6], to store the grades.
3. Declare a 1D float array, averages[5], to store student averages.
56
4. Use nested loops to prompt the user to enter 6 grades for each of the 5 students and store
them in the grades array. While doing so, calculate the sum for each student and then their
average, storing it in the averages array.
5. Print a table header.
6. Use a loop to iterate through each student:
a. Print the student number.
b. Use an inner loop to print each of their 6 grades.
c. Print their calculated average.
7. Initialize highestAverage and lowestAverage with the average of the first student.
8. Use a loop to iterate through the averages array to find the highestAverage and
lowestAverage.
9. Print the highestAverage.
10. Print the lowestAverage.
Example Input/Output:
Objective:
Write a C++ program that asks the user to enter the elements of two 3x3 matrices. Add the two
matrices and print the resulting matrix.
Clarification:
Matrix addition involves adding corresponding elements of two matrices of the same dimensions.
The resulting matrix will have the same dimensions.
57
Steps:
1. Declare three 2D integer arrays of size 3x3: matrix1, matrix2, and resultMatrix.
2. Use nested loops to prompt the user to enter elements for matrix1.
3. Use nested loops to prompt the user to enter elements for matrix2.
4. Use nested loops to add the matrices:
a. Iterate through rows i from 0 to 2.
b. Iterate through columns j from 0 to 2.
c. Set resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j].
5. Print the resultMatrix in a 3x3 format.
Example Input/Output:
Objective:
Write a C++ program that asks the user to enter the elements of two 3x3 matrices. Multiply the
two matrices and print the resulting matrix.
Clarification:
Matrix multiplication involves a more complex calculation. For each element C[i][j] in the
resulting matrix, it is the sum of the products of elements from row i of the first matrix and
column j of the second matrix.
Steps:
1. Declare three 2D integer arrays of size 3x3: matrix1, matrix2, and resultMatrix.
58
2. Use nested loops to prompt the user to enter elements for matrix1.
3. Use nested loops to prompt the user to enter elements for matrix2.
4. Initialize all elements of resultMatrix to 0.
5. Use triple nested loops to multiply the matrices:
a. Outer loop: Iterate through rows i of resultMatrix from 0 to 2.
b. Middle loop: Iterate through columns j of resultMatrix from 0 to 2.
c. Inner loop: Iterate through k from 0 to 2 (this is for the sum of products).
d. Add matrix1[i][k] * matrix2[k][j] to resultMatrix[i][j].
6. Print the resultMatrix in a 3x3 format.
Example Input/Output:
59
LAB
12 LAB 12: POINTERS
Objective:
Write a C++ program that declares an integer pointer, initializes it with the address of a variable,
and then prints both the address and the value using the pointer.
Steps:
1. Declare an integer variable and assign it a value.
2. Declare an integer pointer.
3. Initialize the pointer with the memory address of the integer variable using the address-of
operator (&).
4. Print the address stored in the pointer.
5. Print the value that the pointer is pointing to (i.e., the value of the original variable) using
the dereference operator (*).
Example Input/Output:
Objective:
Write a C++ program to increment the value of a variable using a pointer and print the incremented
value.
Steps:
1. Declare an integer variable and assign it an initial value.
2. Declare an integer pointer.
3. Initialize the pointer with the address of the integer variable.
4. Increment the value at the address pointed to by the pointer using
(*pointer_variable)++.
5. Print the new value of the variable using the pointer.
60
Example Input/Output:
Original value: 10
Value after increment using pointer: 11
Objective:
Write a C++ program that declares and initializes an array of 10 integers, uses a pointer to iterate
through it, and prints each element.
Steps:
1. Declare and initialize an array of 10 integers.
2. Declare an integer pointer and initialize it with the address of the first element of the array.
3. Use a loop that iterates 10 times. In each iteration:
a. Print the value pointed to by the current pointer position
(*pointer_variable).
b. Increment the pointer to move to the next array element
(pointer_variable++).
Example Input/Output:
Array elements: 1 2 3 4 5 6 7 8 9 10
Objective:
Write a function that takes an array of integers and its size as arguments, and uses a pointer to find
and return the sum of the elements. Demonstrate its usage in the main function.
Steps:
1. Define a function getSum that accepts an int* (pointer to the first element) and an int
(size) as arguments.
2. Inside the getSum function:
a. Initialize a sum variable to 0.
b. Use a loop that iterates from 0 up to size - 1.
c. In each iteration, add the value *(array_pointer + i) to sum.
d. Return the sum.
61
3. In the main function:
a. Declare and initialize an integer array.
b. Call the getSum function, passing the array name (which decays to a pointer to its
first element) and its size.
c. Print the returned sum.
Example Input/Output:
Array sum: 55
Objective:
Write a function that swaps two integers using pointers and demonstrate its usage in the main
function.
Steps:
1. Define a function swapIntegers that accepts two int* arguments (pointers to the
integers to be swapped).
2. Inside the swapIntegers function:
a. Declare a temporary integer variable.
b. Store the value pointed to by the first pointer (*ptr1) into the temporary variable.
c. Assign the value pointed to by the second pointer (*ptr2) to the location pointed
to by the first pointer (*ptr1 = *ptr2).
d. Assign the value from the temporary variable to the location pointed to by the
second pointer (*ptr2 = temp).
3. In the main function:
a. Declare two integer variables and assign them values.
b. Print their original values.
c. Call the swapIntegers function, passing the addresses of the two variables
(&variable1, &variable2).
d. Print their values again to show they have been swapped.
Example Input/Output:
62
12.6 Function to Return Pointer to Maximum Element in Array
Objective:
Write a function that returns a pointer to the maximum element in an array and print the
maximum value in the main function.
Steps:
1. Define a function findMaxElementPointer that accepts an int* (pointer to the first
element) and an int (size) as arguments, and returns an int*.
2. Inside the findMaxElementPointer function:
a. Initialize an int* maxPtr to point to the first element of the array (arr).
b. Use a loop that iterates from i = 1 up to size - 1.
c. Compare the value at *(arr + i) with the value at *maxPtr.
d. If *(arr + i) is greater, update maxPtr to point to (arr + i).
e. Return maxPtr.
3. In the main function:
a. Declare and initialize an integer array.
b. Call findMaxElementPointer, storing the returned pointer in an int*.
c. Print the value pointed to by the returned pointer (*returned_pointer).
Example Input/Output:
Objective:
Write a program that sorts an array using pointer arithmetic (e.g., bubble sort) and print the sorted
array.
Clarification:
Bubble sort works by repeatedly stepping through the array, comparing adjacent elements and
swapping them if they are in the wrong order. This process is repeated until no swaps are needed.
Steps:
1. Declare and initialize an array of integers.
2. Get the size of the array.
3. Implement Bubble Sort using pointer arithmetic:
63
a. Use an outer loop that iterates from i = 0 to size - 2.
b. Use an inner loop that iterates from j = 0 to size - 1 - i.
c. Inside the inner loop, compare *(array_name + j) with *(array_name + j
+ 1).
d. If *(array_name + j) is greater than *(array_name + j + 1), swap their
values using a temporary variable.
4. After sorting, iterate through the array using pointer arithmetic and print each element.
Example Input/Output:
Original array: 64 25 12 22 11
6.
Sorted
7. array: 11 12 22 25 64
Objective:
Write a program that allocates memory for an integer, assigns a value, prints it, and then frees the
memory.
Steps:
1. Declare an integer pointer.
2. Dynamically allocate memory for a single integer using new int; and assign the returned
address to the pointer.
3. Assign a value to the dynamically allocated integer using the dereference operator
(*pointer_variable = value).
4. Print the value of the dynamically allocated integer using the pointer.
5. Free the dynamically allocated memory using delete pointer_variable;.
6. Set the pointer to nullptr to avoid dangling pointer issues.
Example Input/Output:
64
12.9 Dynamically Allocate, Populate, Print, and Free Array
Memory
Objective:
Write a program that allocates memory dynamically for an array of integers, populate it with
values, print the values, and then free the memory.
Steps:
1. Prompt the user to enter the desired size of the array.
2. Declare an integer pointer.
3. Dynamically allocate memory for an array of that size using new int[size]; and
assign the returned address to the pointer.
4. Use a loop to prompt the user to enter values and populate the dynamically allocated array
using pointer arithmetic (*(pointer_variable + i)).
5. Use another loop to print the values of the dynamically allocated array using pointer
arithmetic.
6. Free the dynamically allocated array memory using delete[] pointer_variable;.
7. Set the pointer to nullptr.
Example Input/Output:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Array elements: 10 20 30 40
Memory freed.
Objective:
Write a program that uses a pointer to a function as an argument to another function. The program
should define two functions: one that adds two numbers and another that subtracts two numbers.
The main function should call a third function, passing the address of either the addition or
subtraction function as an argument, along with two integers. The third function should then use
the passed function pointer to perform the operation and display the result.
65
Steps:
1. Define a function addNumbers that takes two integers and returns their sum.
2. Define a function subtractNumbers that takes two integers and returns their
difference.
3. Define a third function performOperation that takes three arguments:
a. A pointer to a function that takes two integers and returns an integer (int
(*operation)(int, int)).
b. Two integers (num1, num2).
4. Inside performOperation, call the passed function pointer with num1 and num2, and
store the result.
5. Print the result.
6. In the main function:
a. Declare two integer variables for inputs.
b. Call performOperation, passing the address of addNumbers
(&addNumbers), along with the two integers.
c. Call performOperation again, passing the address of subtractNumbers
(&subtractNumbers), along with the two integers.
Example Input/Output:
Result of addition: 30
Result
7. of subtraction: -10
Objective:
Write a program that takes a C-string as input and converts all its characters to uppercase using
pointer arithmetic.
Steps:
1. Declare a character array (C-string) and initialize it or take input from the user.
2. Declare a character pointer and initialize it to point to the beginning of the C-string.
3. Use a while loop that continues as long as the character pointed to by the pointer is not the
null terminator (\0).
4. Inside the loop:
a. Convert the character pointed to by the pointer to uppercase using toupper()
(from <cctype> header). Assign the result back to *pointer_variable.
b. Increment the pointer (pointer_variable++) to move to the next character.
5. After the loop, print the modified C-string.
66
Example Input/Output:
Enter a string: Hello World!
Uppercase string: HELLO WORLD!
Objective:
Write a program that dynamically allocates an array large enough to hold a user-defined number
of test scores. Once all the scores are entered, the array should be passed to a function that sorts
them in ascending order. Another function should be called that calculates the average score. The
program should display the sorted list of scores and averages with appropriate headings. Use
pointer notation rather than array notation.
Steps:
1. In main:
a. Prompt the user for the number of test scores (numScores).
b. Dynamically allocate memory for numScores double-precision floating-point
numbers using new double[numScores]. Store the address in a double*
pointer.
c. Use a loop to prompt the user to enter each test score and store it in the allocated
memory using pointer notation (*(scoresPtr + i)).
2. Define a function sortScores that takes a double* (pointer to scores array) and an int
(size) as arguments.
a. Implement a sorting algorithm (e.g., Bubble Sort or Selection Sort) using pointer
arithmetic to access and swap elements.
3. Define a function calculateAverage that takes a double* (pointer to scores array) and
an int (size) as arguments, and returns a double.
a. Initialize sum = 0.0.
b. Use a loop to iterate through the array using pointer arithmetic (*(scoresPtr +
i)) and add each score to sum.
c. Return sum / size.
4. In main (after input):
a. Call sortScores to sort the dynamically allocated array.
b. Call calculateAverage to get the average score.
c. Print the sorted list of scores with an appropriate heading, iterating through the
array using pointer arithmetic.
d. Print the calculated average score with an appropriate heading.
e. Free the dynamically allocated memory using delete[] scoresPtr;.
f. Set scoresPtr = nullptr;.
67
Example Input/Output:
Objective:
Write a function that determines the median of a sorted array. The function should take an array of
numbers and an integer indicating the size of the array and return the median of the values in the
array. You may assume the array is already sorted. Use pointer notation.
Steps:
1. Define a function findMedian that takes an int* (pointer to the sorted array) and an int
(size) as arguments, and returns a double.
2. Inside findMedian:
a. Check if the size is odd: i. If true, the median is the element at the middle index:
*(arr + size / 2).
b. Check if the size is even: i. If true, the median is the average of the two middle
elements: (*(arr + size / 2 – 1) + *(arr + size / 2)) / 2.0.
c. Return the calculated median.
3. In main:
a. Declare and initialize a sorted integer array.
b. Call findMedian, passing the array and its size.
c. Print the returned median value.
Example Input/Output:
Array (odd size): 1 3 5 7 9
Median: 5.00
68
12.14 Statistical Data for Movies: Average, Median, Mode
(Dynamic Allocation)
Objective:
Write a program that can be used to gather statistical data about the number of movies college
students see in a month. The program should ask the user how many students were surveyed and
dynamically allocate an array of that size. The program should then allow the user to enter the
number of movies each student has seen. The program should then calculate the average, median,
and mode of the values entered.
Clarification:
For the mode, you will need to count frequencies manually, which is easier on a sorted array. If
multiple modes exist, printing any one of them is acceptable.
Steps:
1. In main:
a. Prompt the user for the number of students surveyed (numStudents).
b. Dynamically allocate memory for numStudents integers (movie counts) using
new int[numStudents]. Store the address in an int* pointer.
c. Use a loop to prompt the user to enter the number of movies seen by each student
and store it in the allocated memory using pointer notation (*(moviesPtr +
i)).
2. Sorting Function (e.g., sortMovies):
a. Define a function that takes int* and int arguments and sorts the array using
pointer arithmetic (e.g., Bubble Sort). This is necessary for calculating the median
and simplifies mode calculation.
3. Average Function (e.g., calculateAverage):
a. Define a function that takes int* and int arguments and returns a double. Sum
elements using pointer arithmetic and divide by size.
4. Median Function (e.g., findMedian):
a. Define a function that takes int* and int arguments and returns a double.
5. Mode Function (e.g., findMode):
a. Define a function that takes int* and int arguments and returns an int.
o Initialize mode = -1, maxCount = 0.
o Iterate through the sorted array (using pointer arithmetic for i).
o For each element *(arr + i), count its occurrences by iterating from
j = i to size - 1.
o If the currentCount is greater than maxCount, update maxCount and
set mode = *(arr + i).
o Skip elements that have already been counted (e.g., by advancing i past
69
duplicates).
o Return mode.
6. In main (after input):
a. Call sortMovies to sort the dynamically allocated array.
b. Call calculateAverage and print the result.
c. Call findMedian and print the result.
d. Call findMode and print the result.
e. Free the dynamically allocated memory using delete[] moviesPtr;.
f. Set moviesPtr = nullptr;.
Example Input/Output:
Statistical Data:
Average: 2.43
Median: 3.00
Mode: 3
70
LAB
13 LAB 13: STRUCTURES
Objective:
Write a C++ program that defines a Student structure, declares a variable of this type, assigns
values to its members, and then prints these values.
Steps:
1. Define a structure named Student with members name (string), id (int), age (int), and
gpa (float).
2. In the main function, declare a variable of type Student.
3. Assign sample values to each member of the Student variable.
4. Print the values of each member to the console.
Example Input/Output:
Student Information:
Name: Alice Banda
ID: 1001
Age: 20
GPA: 3.85
Objective:
Write a C++ program to define a Book structure, initialize a variable of this type with members
title (string), author (string), pages (int), and price (float), and then print the values of these
members.
Steps:
1. Define a structure named Book with members title (string), author (string), pages
(int), and price (float).
2. In the main function, declare and directly initialize a Book variable with sample values.
3. Print the values of each member to the console.
Example Input/Output:
Book Details:
Title: The Great Adventure
Author: John Phiri
Pages: 320
Price: 2500.99
71
13.3 Customer Structure Declaration and Initialization (Fixed
Values)
Objective:
Write a C++ program that defines a Customer structure with specified information, declares a
structure variable, initializes it with some fixed values, and then prints the information.
Steps:
1. Define a structure named Customer with members name (string), address (string),
category (char), discountPercent (float), and totalInvoiceYTD (float).
2. In the main function, declare a variable of type Customer.
3. Assign sample fixed values to each member of the Customer variable.
4. Print the customer information to the console.
Example Input/Output:
Customer Information:
Name: Jane Banda
Address: P/Bag 303, Chichiri
Category: A
Discount: 10.50%
Total Invoice YTD: MK12500.75
Objective:
Modify the previous program to allow the user to enter the customer information for a single
customer, then print it.
Steps:
1. Define the Customer structure as in the previous question.
2. In the main function, declare a variable of type Customer.
3. Prompt the user to enter values for each member (name, address, category,
discountPercent, totalInvoiceYTD).
4. Read the user's input for each member. Use getline(cin >>ws, [Link]);
for strings with spaces.
5. Print the entered customer information to the console.
72
Example Input/Output:
Customer Information:
Name: Robert Mwaza
Address: P/Bag 303, Chichiri
Category: B
Discount: 5.00%
Total Invoice YTD: MK 5000.25
Objective:
Modify the previous program to declare a structure array for 3 customers, allow the user to enter
information for all three, and then print all their details.
Steps:
1. Define the Customer structure as before.
2. In the main function, declare an array of Customer variables of size 3 (e.g., Customer
customers[3];).
3. Use a for loop to iterate 3 times:
a. Inside the loop, prompt the user to enter information for the current customer
(e.g., "Enter details for Customer 1:").
b. Read input for each member of customers[i].
4. Use another for loop to iterate through the array:
a. Inside the loop, print the information for customers[i] with a heading (e.g.,
"Details for Customer 1:").
73
Example Input/Output:
74
13.6 Union for Character and Integer
Objective:
Write a C++ program to show how a union shares memory by storing a character and an integer
and displaying their values.
Steps:
Example Input/Output:
Character value: A
Integer value: 65
Steps:
1. Define an enumeration ErrorCode:
a. Enumerators:
o SUCCESS = 0
o FILE_NOT_FOUND = 1
o ACCESS_DENIED = 2
2. In main() function:
a. Declare an ErrorCode variable.
b. Assign an error code.
c. Display the error code and its integer value.
Example Input/Output:
Error: FILE_NOT_FOUND
Code: 1
75
13.8 Employee Structure Array Iteration
Objective:
Write a program to create an array of Employee structures to store information about three
employees, and then iterate through the array to print each employee's details.
Steps:
1. Define a structure named Employee with members name (string), id (int), and salary
(float).
2. In the main function, declare an array of Employee variables of size 3.
3. Initialize the array with sample data for three employees.
4. Use a for loop to iterate through the Employee array.
5. Inside the loop, print the name, id, and salary of each employee.
Example Input/Output:
Employee Details:
76
13.9 Car Structure with Pointers and Update Function
Objective:
Write a program that defines a Car structure, uses pointers to modify and print its members, and
includes a function updateCarPrice that takes a pointer to a Car structure and a new price to
update the car's price.
Steps:
1. Define a structure named Car with members make (string), model (string), year (int),
and price (float).
2. Define a function updateCarPrice that takes two arguments: an int* to a Car structure
(Car* carPtr), and a float for the newPrice. Inside, update carPtr-> price =
newPrice;.
3. In the main function:
a. Declare a Car variable and assign initial values.
b. Declare a Car* pointer and initialize it to the address of the Car variable (Car*
myCarPtr = &myCar;).
c. Print the initial Car details using the pointer (myCarPtr->make, etc.).
d. Call updateCarPrice, passing myCarPtr and a new price.
e. Print the updated Car details using the pointer to demonstrate the change.
Example Input/Output:
77
13.10 Nested Employee Structure
Objective:
Write a program that defines a nested Employee structure, initializes its members (including the
nested address), and prints its details.
Steps:
1. Define a structure named Address with members street (string), city (string), and
postcode (string).
2. Define a structure named Employee with members name (string), id (int), salary
(float), and address (of type Address).
3. In the main function, declare an Employee variable.
4. Assign sample values to all members, including accessing nested Address members (e.g.,
[Link] = "105 Chipembere";).
5. Print the Employee details, including the nested Address details.
Example Input/Output:
Employee Details:
Name: Sarah Chingwe
ID: 205
Salary: 68000.00
Address:
Street: 15 Henderson
City: Blantyre
Postcode: 90210
Objective:
Write a program that defines a Rectangle structure, provides a function to calculate its area, and
another function to update its dimensions using a reference, demonstrating their usage.
Steps:
1. Define a structure named Rectangle with members length (float) and width (float).
2. Define a function calculateArea that takes a Rectangle object by value (Rectangle
rect) and returns [Link] * [Link].
3. Define a function updateDimensions that takes a Rectangle object by reference
(Rectangle& rect), a float newLength, and a float newWidth. Inside, set
[Link] = newLength; and [Link] = newWidth;.
78
4. In the main function:
a. Declare a Rectangle variable and initialize its dimensions.
b. Call calculateArea with the Rectangle and print the result.
c. Call updateDimensions, passing the Rectangle variable and new
length/width values.
d. Call calculateArea again with the updated Rectangle and print the new
result.
Example Input/Output:
Initial Rectangle: Length = 10.0, Width = 5.0
Area: 50.00
Updating dimensions...
Objective:
Write a program that defines a SavingsAccount structure and provides functions for getting
data, showing data, depositing, and withdrawing, all accessible via a menu in the main function.
Steps:
1. Define a structure SavingsAccount with members accountNumber (string),
accountBalance (float), interestRate (float), and averageMonthlyBalance
(float).
2. Define the following functions, each taking a SavingsAccount& reference for
modification, or const SavingsAccount& for display:
a. getAccountData(SavingsAccount& account):
o Prompts user for all account details.
b. showAccountData(const SavingsAccount& account):
o Displays all account details.
c. deposit(SavingsAccount& account, float amount):
o Adds amount to accountBalance.
d. withdraw(SavingsAccount& account, float amount):
o Subtracts amount from accountBalance (add basic check for
sufficient funds).
79
3. In the main function:
a. Declare a SavingsAccount variable.
b. Implement a do-while loop for the menu.
c. Display menu options (Enter Data, Show Data, Deposit, Withdraw, Exit).
d. Read user's choice.
e. Use a switch statement to call the appropriate function based on the choice.
f. Include basic input validation and messages for user feedback.
Example Input/Output:
Account Details:
Account Number: 12345
Balance: $1000.00
Interest Rate: 1.50%
Avg Monthly Balance: MK950.00
1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit
Enter your choice: 3
80
Enter withdrawal amount: 150.00
Withdrawal successful! New balance: MK1050.00
1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit
Objective:
Write a program using a structure to store sales data for company divisions (East, West, North,
South). It should use functions to calculate total and average sales, and to display the results for
each division.
Steps:
1. Define a structure Division with members: name (string), q1Sales, q2Sales,
q3Sales, q4Sales (all float), totalAnnualSales (float), and
averageQuarterlySales (float).
2. Define a function calculateSalesData that takes a Division& (reference) argument.
a. Inside, prompt the user to enter quarterly sales for the given division's name.
b. Read the four quarterly sales values.
c. Calculate totalAnnualSales and averageQuarterlySales and store them
in the structure.
3. Define a function displayDivisionData that takes a const Division& (reference)
argument.
a. Inside, print the division name, its total annual sales, and its average quarterly
sales with appropriate formatting.
4. In the main function:
a. Declare four Division variables: east, west, north, south.
81
b. Assign initial names to each division (e.g., [Link] = "East";).
c. Call calculateSalesData for each of the four division variables.
d. Call displayDivisionData for each of the four division variables.
Example Input/Output:
Division: West
Total Annual Sales: MK410000.00
Average Quarterly Sales: MK102500.00
Division: North
Total Annual Sales: MK337000.00
Average Quarterly Sales: MK84250.00
Division: South
Total Annual Sales: MK610000.00
Average Quarterly Sales: MK152500.00
82
13.14 Monthly Budget Tracking
Objective:
Write a program that defines a MonthlyBudget structure to track expense categories, initializes
one with budgeted amounts, allows the user to enter actual spent amounts, and then generates a
report comparing budget to actual and showing totals.
Steps:
1. Define a structure MonthlyBudget with individual float members for each expense
category listed: housing, utilities, householdExpenses, transportation,
food, medical, insurance, entertainment, clothing, miscellaneous.
2. Define a function getUserSpentAmounts that takes a MonthlyBudget& (reference)
argument.
a. Inside, prompt the user to enter the actual amount spent for each category and
read the input.
3. Define a function generateBudgetReport that takes two const MonthlyBudget&
arguments: budgeted and actual.
a. Initialize totalOverUnder = 0.0.
b. For each category:
i. Calculate difference = [Link] -
[Link].
ii. Add difference to totalOverUnder.
iii. Print the category name, budgeted amount, actual amount, and
the difference (indicating "over" or "under").
c. After all categories, print the totalOverUnder for the month.
4. In the main function:
a. Declare two MonthlyBudget variables: budgetedAmounts and
actualSpent.
b. Initialize budgetedAmounts with the provided fixed values.
c. Call getUserSpentAmounts with actualSpent to get user input.
d. Call generateBudgetReport, passing budgetedAmounts and
actualSpent.
83
Example Input/Output:
Please enter the actual amounts spent for the past month:
Enter actual Housing expenses: 5100.00
Enter actual Utilities expenses: 1400.00
Enter actual Household expenses: 700.00
Enter actual Transportation expenses: 550.00
Enter actual Food expenses: 2400.00
Enter actual Medical expenses: 300.00
Enter actual Insurance expenses: 1000.00
Enter actual Entertainment expenses: 1600.00
Enter actual Clothing expenses: 700.00
Enter actual Miscellaneous expenses: 450.00
84
LAB
14 LAB 14: STRINGS MANIPULATION
Objective:
Write a C++ program that prompts the user for a character and prints its corresponding character
code (ASCII or Unicode value).
Steps:
1. Declare a char variable to store the input character.
2. Prompt the user to enter a character.
3. Read the character from the input.
4. Print the character itself, followed by its integer representation (character code).
Example Output:
Enter a character: S
The character 'S' has code 83
Objective:
Write a C++ program that prompts the user for a character and an integer, and then prints the
character the specified number of times.
Steps:
1. Declare a char variable for the character and an int variable for the count.
2. Prompt the user to enter a character.
3. Read the character.
4. Prompt the user to enter an integer (the number of times to print).
5. Read the integer.
6. Use a for loop that iterates from 0 up to (but not including) the entered integer count.
7. Inside the loop, print the character.
Example Output:
Enter a character: #
Enter how many times to print: 7
Output:
#######
85
14.3 Length of Text from Keyboard
Objective:
Write a C++ program that reads a line of text (string) from the keyboard and prints its total length
(number of characters).
Steps:
1. Declare a string variable to store the input text.
2. Prompt the user to enter a line of text.
3. Read the entire line of text, including spaces, using getline(cin,
string_variable);.
4. Print the length of the string using the length() member function of string.
Example Input/Output:
Objective:
Write a C++ program that prompts the user for two words and determines their lexicographical
order (which comes first alphabetically, or if they are equal).
Steps:
1. Declare two string variables to store the two words.
2. Prompt the user to enter the first word.
3. Read the first word.
4. Prompt the user to enter the second word.
5. Read the second word.
6. Use if-elseif statements to compare the two strings:
a. If word1 == word2, print that they are equal.
b. If word1 < word2, print that word1 is lexicographically smaller.
c. Else (if word1 > word2), print that word1 is lexicographically greater.
Example Output:
86
14.5 String Length Using Character Array and Loop
Objective:
Write a C++ program to calculate and print the length of a string stored in a character array,
manually counting characters until the null terminator (\0) is found.
Steps:
1. Declare a char array (C-style string) and initialize it with a string literal.
2. Initialize an integer variable length to 0.
3. Use a while loop that continues as long as the character at str[length] is not the null
terminator (\0).
4. Inside the loop, increment the length variable.
5. After the loop, length will hold the count of characters (excluding the null terminator), so
print it.
Example Input/Output:
Objective:
Write a C++ program that takes a string input from the user, accesses its third character, changes
it to 'z', and then prints the modified string.
Steps:
1. Declare a string variable to hold the input string.
2. Prompt the user to enter a string.
3. Read the string from the input.
4. Check if the string's length is at least 3 characters.
5. If the string is long enough, modify the character at index 2 (the third character) to 'z'
using bracket notation (string_variable[2] = 'z';).
6. Print the modified string.
7. If the string is too short, print an appropriate message.
Example Input/Output:
87
14.7 Reverse String Function (In Place)
Objective:
Write a C++ function void reverseString(char str[]) that reverses a C-style string in
place. Demonstrate its usage in the main function.
Steps:
1. Define reverseString function:
a. Accepts a char str[] as input.
b. Find the length of the string (e.g., using strlen from <cstring>).
c. Initialize two index variables: left = 0 and right = length - 1.
d. Use a while loop that continues as long as left < right.
e. Inside the loop, swap the characters at str[left] and str[right] (using a
temporary char variable).
f. Increment left and decrement right.
2. In main function:
a. Declare a char array and initialize it with a test string.
b. Print the original string.
c. Call reverseString with the array.
d. Print the reversed string.
Example Input/Output:
Objective:
Write a C++ function int stringLength(const char str[]) that calculates and returns
the length of a C-style string without using the built-in strlen function. Demonstrate its usage in
the main function.
Steps:
1. Define stringLength function:
a. Accepts a const char str[] as input.
b. Initialize an integer count to 0.
c. Use a while loop that continues as long as the character at str[count] is not the
null terminator (\0).
88
d. Inside the loop, increment count.
e. Return the final count.
2. In main function:
a. Declare a char array and initialize it with a test string.
b. Call stringLength with the array.
c. Print the returned length.
Example Input/Output:
assuming string "programming"
The length of the string is: 11
Objective:
Write a C++ program that prompts the user to enter a string, then counts and prints the number of
vowels and consonants within that string.
Steps:
1. Declare a string variable for the input string.
2. Initialize vowelCount and consonantCount to 0.
3. Prompt the user to enter a string.
4. Read the string.
5. Iterate through each character of the string (e.g., using a for loop with index).
6. For each character:
a. Convert the character to lowercase using tolower() (from <cctype>) to simplify
vowel checking.
b. Check if the character is an alphabet letter (using isalpha() from <cctype>).
c. If it is an alphabet, check if it's one of 'a', 'e', 'i', 'o', 'u'. If yes,
increment vowelCount.
d. Otherwise (if it's an alphabet but not a vowel), increment consonantCount.
7. Print the final vowelCount and consonantCount.
Example Input/Output:
89
14.10 Check if String is Palindrome
Objective:
Write a C++ function bool isPalindrome(const char str[]) that determines if a given
C-style string is a palindrome. Demonstrate its usage in the main function.
Clarification:
For this problem, we will consider only the characters in the string, ignoring case and any non-
alphanumeric characters for a true palindrome check.
Steps:
1. Define isPalindrome function:
a. Accepts a const char str[] as input.
b. Get the length of the string (using strlen).
c. Initialize left = 0 and right = length - 1.
d. Use a while loop that continues as long as left < right.
e. Inside the loop:
i. Convert characters to lowercase (using tolower()) for case-insensitive
comparison.
ii. Skip non-alphanumeric characters from left side.
iii. Skip non-alphanumeric characters from right side.
iv. If str[left] is not equal to str[right], return false.
v. Increment left and decrement right.
f. If the loop completes, return true.
2. In main function:
a. Declare a char array and initialize it with a test string.
b. Call isPalindrome with the array.
c. Print whether the string is a palindrome or not.
Example Input/Output:
90
14.11 Concatenate Two Strings Function
Objective:
Create a function char* concatenateStrings(const char str1[], const char str2[])
that concatenates two C-style strings and returns a pointer to the new dynamically allocated string.
Steps:
1. Define concatenateStrings:
a. Accepts const char str1[] and const char str2[].
b. Use strlen() to determine their lengths.
c. Allocate memory for the new string (length1 + length2 + 1).
d. Use strcpy() to copy str1 into the new string.
e. Use strcat() to append str2.
f. Return the new string.
2. In main:
a. Initialize two test strings.
b. Call concatenateStrings() and store the result.
c. Print the result.
d. Free memory using delete[].
Example Output:
Input: str1 = "Hello ", str2 = "World!"
Output: Concatenated string: Hello World!
Objective:
Write a C++ program that takes a sentence as input from the user and counts the total number of
words in it, assuming words are separated by single or multiple spaces.
Steps:
1. Declare a string variable to hold the input sentence.
2. Initialize wordCount = 0 and bool inWord = false.
3. Prompt the user to enter a sentence.
4. Use getline to read the entire line of input.
5. Loop through each character of the string:
a. If the character is a space, set inWord = false.
b. If the character is not a space and inWord == false:
o Increment wordCount.
o Set inWord = true.
6. Print the final wordCount.
91
Example Output:
Input: This is a sample sentence.
Output: Number of words: 5
Objective:
Write a C++ program that takes a given string as input from the user and converts all its
lowercase characters to uppercase without using built-in string manipulation functions.
Steps:
1. Declare a string variable for the input.
2. Prompt the user to enter a string and read it.
3. Loop through each character of the string:
a. If the character is between 'a' and 'z', convert it to uppercase using:
char_variable = char_variable - ('a' - 'A');
4. Print the modified uppercase string.
Example Input/Output:
Enter a string: c++ programming
Uppercase string: C++ PROGRAMMING
Objective:
Write a C++ function that accepts a C-style string as an argument and returns the number of
words in it. Demonstrate the function with user input.
Steps:
1. Define countWords Function:
a. Accepts const char* str.
b. Initialize wordCount = 0, bool inWord = false.
c. Use a while loop to iterate through the string until *str == '\0'.
d. Inside the loop:
o If isalpha(*str) and inWord == false, set inWord = true, increment
wordCount.
o If not an alphabet character and inWord == true, set inWord = false.
o Move to the next character.
92
2. In main:
a. Declare a char array (e.g., char input[256];).
b. Prompt and read a sentence using [Link].
c. Call countWords(input) and display the result.
Example Input/Output:
Enter a sentence: Four score and seven years ago.
Number of words: 7
Objective:
Write a C++ program that takes 10 strings as input, stores them using an array of char*, sorts them
alphabetically by swapping pointers, and prints the sorted list. Use separate functions for reading,
sorting, and printing.
Clarification:
This program will use an array of `char*` (pointers to C-strings) to manage the strings. The
sorting algorithm will swap these pointers, not the actual string content. Selection Sort is suitable
for this.
Steps:
1. Define constants:
a. const int NUM_STRINGS = 10;
b. const int MAX_STR_LEN = 100;
2. readStrings(char* strPointers[], int count):
a. Loop count times:
o Allocate memory using new char[MAX_STR_LEN];.
o Read string using std::[Link].
3. sortStrings(char* strPointers[], int count):
a. Use selection sort to compare using strcmp and swap pointers.
4. printStrings(const char* strPointers[], int count):
a. Loop through the array and print each string.
5. In main:
a. Declare char* strings[NUM_STRINGS];
b. Call readStrings, sortStrings, and printStrings.
c. Use delete[] on each strings[i] to free memory.
93
Example Input/Output:
Sorted Strings:
apple
banana
cherry
date
fig
grape
kiwi
mango
orange
peach
Objective:
Write a C++ program that dynamically manages a list of C-style strings using a 2D array (array of
`char*`). It should provide functions to add a new string, delete an existing string by index, and
print all current strings, ensuring proper memory management for dynamic allocations.
Clarification:
The "2D array" here refers to `char**`, which is a pointer to an array of `char*`. Each `char*`
will point to a dynamically allocated C-string.
Steps:
1. Use global variables or encapsulate in a class:
a. char** stringArray = nullptr;
b. int currentSize = 0;, int capacity = 0;
2. initializeArray(int initialCapacity):
a. Allocate stringArray with new char*[initialCapacity];
b. Set capacity and reset currentSize.
94
3. addString(const char* newStr):
a. Resize if currentSize == capacity.
b. Allocate new memory and copy string using strcpy.
4. deleteString(int index):
a. Free memory at stringArray[index].
b. Shift subsequent elements left.
5. printStrings():
a. If empty, say so.
b. Otherwise, print all strings.
6. freeAllMemory():
a. Loop through and delete[] each string.
b. Then delete[] stringArray.
7. In main:
a. Call initializeArray(5).
b. Use menu-driven interface to interact.
c. Call freeAllMemory() before exit.
Example Input/Output:
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 1 Enter string to add: apple
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 1 Enter string to add: banana
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 3 Strings in array: 0: apple 1: banana
95
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 2 Enter index to delete (0-indexed): 0
String at index 0 deleted.
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 3 Strings in array: 0: banana
Menu:
1. Add String
2. Delete String by Index
3. Print All Strings
4. Exit Enter your choice: 4 Exiting program. Memory freed.
<!-- end list -->
Objective:
Write a C++ function that accepts a C-style string, modifies it in-place to capitalize the first letter
of each sentence, and demonstrates this modification in `main`.
Steps:
1. Define capitalizeSentences(char* str):
a. Use a pointer to iterate through characters.
b. Set bool newSentence = true;
c. If newSentence and character is alphabet, capitalize using toupper, then set
newSentence = false.
d. If the character is ., !, or ?, set newSentence = true.
2. In main:
a. Declare char sentence[256];
b. Read input using std::[Link].
c. Call capitalizeSentences.
d. Display modified string.
Example Input/Output:
Enter a string: this is a test. another sentence here! one
more? yes.
Modified string: This is a test. Another sentence here! One
more? Yes.
96
14.18 Password Validation Program
Objective:
Write a C++ program that prompts a user to enter a password and then validates it against the
following criteria:
a. It must be at least six characters long.
b. It must contain at least one uppercase letter.
c. It must contain at least one lowercase letter.
d. It must contain at least one digit.
The program should display clear messages explaining which criteria are not met.
Steps:
1. Declare a string password;
2. Prompt and read password.
3. Set flags: hasMinLength, hasUppercase, hasLowercase, hasDigit to false.
4. Check length with [Link]() >= 6.
5. Loop through password:
a. Set flags using isupper(), islower(), isdigit().
6. Display appropriate messages:
a. If all flags true → password is valid.
b. Else → print what criteria are missing.
Example Input/Output:
97
LAB
15 LAB 15: CLASSES AND OBJECTS
Objective:
Write a C++ program to define a class Rectangle with private length and width members,
and public methods to set dimensions, calculate area, and display information.
Steps:
1. Define the Rectangle class:
a. Private members: float length;, float width;.
b. Public methods:
o setDimensions(float l, float w): Sets length and width.
Include basic validation (e.g., dimensions must be positive).
o calculateArea(): Returns length * width.
o display(): Prints the length, width, and calculated area.
2. In main function:
a. Declare a Rectangle object.
b. Call setDimensions to set its length and width.
c. Call display to show its details.
Example Input/Output:
Rectangle Dimensions:
Length: 10.00
Width: 5.00
Area: 50.00
Objective:
Write a C++ program to create a class Circle with a private radius member, implement a
constructor to initialize it, and a member function to calculate and display the circle's area.
Steps:
1. Define the Circle class:
a. Private member: float radius;.
98
b. Public members:
o Constructor: Circle(float r): Initializes radius with r. Include
validation (radius must be positive).
o calculateAndDisplayArea(): Calculates area (πr2) and prints it.
Define M_PI or use 3.14159.
2. In main function:
a. Declare a Circle object, passing a radius value to the constructor.
b. Call calculateAndDisplayArea() on the object
Example Input/Output:
Objective:
Write a C++ program to define a class Student with private members name, age, and grade,
implement a parameterized constructor to initialize them, and a function to display student details.
Steps:
1. Define the Student class:
a. Private members: string name;, int age;, float grade;.
b. Public members:
o Parameterized Constructor: Student(string n, int a, float
g): Initializes name, age, and grade.
o displayDetails(): Prints the student's name, age, and grade.
2. In main function:
a. Declare a Student object, passing initial values for name, age, and grade to the
constructor.
b. Call displayDetails() on the object.
Example Input/Output:
Student Details:
Name: John Phiri
Age: 20
Grade: 85.50
99
15.4 Book Class with Default Constructor and Destructor
Objective:
Write a C++ program to implement a class Book with private members title, author, and price.
Include a default constructor to initialize these, and a destructor that prints a message when a
Book object is destroyed.
Steps:
1. Define the Book class:
a. Private members: std::string title;, std::string author;,
float price;.
b. Public members:
o Default Constructor: Book(): Initializes title, author to default
strings (e.g., "Untitled", "Unknown Author") and price to 0.0.
o Destructor: ~Book(): Prints a message indicating which book object
is being destroyed (e.g., "Book 'Title' destroyed.").
o displayDetails(): Prints the book's title, author, and price.
o setTitle(string t), setAuthor(string a), setPrice(float
p): Setter methods (optional but good for demonstration).
2. In main function:
a. Create Book objects. Observe the destructor messages when objects go out of
scope.
b. You can set some values and display them to confirm the default constructor
works.
Example Input/Output:
Book Details:
Title: Default Title
Author: Default Author
Price: 0.00
Book 'Default Title' destroyed. (This message appears when
book1 goes out of scope)
100
15.5 Point Class with Copy Constructor
Objective:
Write a C++ program to implement a class Point representing a 2D coordinate, including a copy
constructor that correctly copies the values of another Point object. Demonstrate its action by
creating and displaying two objects.
Steps:
1. Define the Point class:
a. Private members: int x;, int y;.
b. Public members:
o Parameterized Constructor: Point(int xVal, int yVal):
Initializes x and y.
o Copy Constructor: Point(const Point& other): Initializes x =
other.x; and y = other.y;. Print a message indicating copy
constructor usage.
o display(): Prints the x and y coordinates.
2. In main function:
a. Create a Point object (e.g., Point p1(10, 20);).
b. Create a second Point object using the copy constructor (e.g., Point p2 = p1;
or Point p2(p1);).
c. Call display() for both p1 and p2 to show they have the same values.
d. Optionally, modify p1 and show p2 remains unchanged (demonstrating deep
copy if pointers were involved, but for simple types, it's just value copy).
Example Input/Output:
Original Point (p1): (10, 20)
Copy constructor called.
Copied Point (p2): (10, 20)
101
15.6 Employee Class Array with User Input
Objective:
Write a C++ program to create an Employee class with private members name, id, and salary.
Implement methods to accept and display employee details. In main, create an array of Employee
objects, take user input for each, and then display all their details.
Steps:
1. Define the Employee class:
a. Private members: std::string name;, int employeeID;, float
salary;.
b. Public methods:
o acceptDetails(): Prompts the user to enter name, employeeID,
and salary, and reads them into the object's members.
o displayDetails(): Prints the employee's name, employeeID, and
salary.
2. In main function:
a. Define a constant for the number of employees (e.g., 3).
b. Declare an array of Employee objects (e.g., Employee
employees[NUM_EMPLOYEES];).
c. Use a for loop to iterate through the array:
o For each element employees[i], call
employees[i].acceptDetails().
d. Use another for loop to iterate through the array:
o For each element employees[i], call
employees[i].displayDetails().
102
Example Input/Output:
Employee 2:
Name: Bob Kamba
ID: 102
Salary: 72500.50
Employee 3:
Name: Charlie Zathu
ID: 103
Salary: 60000.75
Objective:
Design a C++ class Date to store month, day, and year. Implement a three-parameter default
constructor that initializes the date, using default values (1, 1, 2025) if no arguments are
passed or if invalid values are provided. Include member functions to print the date in three
different formats.
103
Input Validation:
Month (1-12), Day (1-31), Year (1964-2025).
Steps:
1. Define the Date class:
a. Private members: int month;, int day;, int year;.
b. Private helper function: isValidDate(int m, int d, int y):
o Checks if the given month, day, and year are within valid ranges. Returns
true if valid, false otherwise.
c. Public members:
o Three-parameter default constructor: Date(int m = 1, int d = 1,
int y = 2025):
▪ Calls isValidDate. If valid, assign m, d, y to members.
▪ If invalid, assign default values (1, 1, 2025) to members.
o printFormat1(): Prints M/D/YY (e.g., 3/15/25).
o printFormat2(): Prints Month DD, YYYY (e.g., March 15, 2025). Needs
an array of month names.
o printFormat3(): Prints DD Month YYYY (e.g., 15 March 2025).
2. In main function:
a. Create several Date objects to demonstrate:
o An object with valid parameters.
o An object with invalid parameters.
o An object with no parameters (uses default constructor values).
b. Call all three printFormat functions for each Date object.
Example Input/Output:
104
15.8 Phone Manufacturing Plant Class
Objective:
Design a C++ class for a phone manufacturing plant to calculate the number of days required to
produce a given number of phones, assuming a production rate of 10 phones/hour and two 8-hour
shifts per day. Prompt the user for the order quantity and display the production time in days.
Input Validation:
Number of phones ordered must not be less than 0.
Steps:
1. Define constants: PHONES_PER_HOUR = 10;, HOURS_PER_SHIFT = 8;,
SHIFTS_PER_DAY = 2;.
2. Define the PhonePlant class:
a. Private members: (Optional, might not need any if calculations are done directly
in a method based on input).
b. Public methods:
o Constructor: A default constructor (no specific state to initialize).
o calculateDays(int numPhonesOrdered):
▪ Calculates totalHoursNeeded = numPhonesOrdered /
(float)PHONES_PER_HOUR;.
▪ Calculates hoursPerDay = HOURS_PER_SHIFT *
SHIFTS_PER_DAY;.
▪ Calculates daysNeeded = totalHoursNeeded / hoursPerDay;.
▪ Use ceil() from <cmath> to round up to the nearest whole day.
▪ Return daysNeeded.
3. In main function:
a. Declare an int variable for numPhonesOrdered.
b. Use a do-while loop for input validation:
o Prompt the user to enter the number of phones ordered.
o Read the input.
o Loop until numPhonesOrdered is non-negative.
c. Declare a PhonePlant object.
d. Call calculateDays on the object, passing numPhonesOrdered.
e. Print the calculated number of days.
105
Example Input/Output:
106
LAB
16 LAB 16: INHERITANCE
Objective:
Implement a base class Person with name and age. Derive a Student class that adds grade.
Demonstrate setting and getting values for all members of a Student object.
Steps:
1. Define Person class:
a. Private members: string name;, int age;.
b. Public methods: Constructor, setName(), setAge(), getName(),
getAge(), displayPerson().
2. Define Student class (inherits from Person):
a. Private member: float grade;.
b. Public methods: Constructor, setGrade(), getGrade(),
displayStudent().
3. In main function:
a. Create a Student object.
b. Set name and age using Person's methods.
c. Set grade using Student's method.
d. Display all details using Student's display method (which can call Person's
display).
Example Input/Output:
Student Details:
Name: Alice Gondwe
Age: 20
Grade: 88.50
Objective:
Create a base class Shape with a virtual area() method. Derive Rectangle and Circle from
Shape, each implementing area() to calculate their respective areas. Demonstrate calculating
areas using base class pointers/references (polymorphism).
107
Steps:
1. Define Shape class:
a. Public method: virtual float area() = 0; (pure virtual function).
b. Virtual Destructor: virtual ~Shape() {} (good practice for base classes
with virtual functions).
2. Define Rectangle class (inherits from Shape):
a. Private members: float length;, float width;.
b. Public methods: Constructor, float area() (implements length *
width).
3. Define Circle class (inherits from Shape):
a. Private member: float radius;.
b. Public methods: Constructor, float area() (implements M_PI * radius *
radius).
4. In main function:
a. Create Rectangle and Circle objects.
b. Declare Shape* pointers and point them to Rectangle and Circle objects.
c. Call area() through the Shape* pointers to demonstrate polymorphism.
d. Remember to delete dynamically allocated objects.
Example Input/Output:
Objective:
Create a base class Vehicle with a parameterized constructor for numWheels. Derive Car with
numSeats and a parameterized constructor that passes arguments to the Vehicle base class
constructor.
Steps:
1. Define Vehicle class:
a. Private member: int numWheels;.
b. Public method: Parameterized constructor Vehicle(int wheels) to initialize
numWheels. displayWheels().
2. Define Car class (inherits from Vehicle):
a. Private member: int numSeats;.
108
b. Public method: Parameterized constructor Car(int wheels, int seats)
using initializer list to call Vehicle constructor: Car(...) :
Vehicle(wheels), .... displayCarDetails().
3. In main function:
a. Create a Car object, passing values for wheels and seats.
b. Call displayCarDetails() to show all initialized members.
Example Input/Output:
Car Details:
Number of Wheels: 4
Number of Seats: 5
Objective:
Implement a base class Employee with protected data members name and salary. Derive a
class Manager that accesses and modifies these protected members directly.
Steps:
1. Define Employee class:
a. Protected members: string name;, double salary;.
b. Public methods: setEmployeeDetails(),
displayEmployeeDetails().
2. Define Manager class (inherits from Employee):
a. Public methods: setManagerDetails() (sets base class name, salary),
displayManagerDetails() (displays base class name, salary and adds
manager-specific info if any).
3. In main function:
a. Create a Manager object.
b. Call setManagerDetails() (which directly accesses name and salary).
c. Call displayManagerDetails() to show the modified values.
Example Input/Output:
Manager Details:
Name: Jane Kaphiri
Salary: 850000.00
109
16.5 Friend Function with Inheritance (Box and ColorBox)
Objective:
Design a base class Box with private dimensions and a friend function displayVolume(). Derive
ColorBox and demonstrate that displayVolume() can calculate the volume for ColorBox
objects as well.
Steps:
1. Define Box class:
a. Private members: double length;, double width;, double height;.
b. Public method: Constructor to set dimensions.
c. Friend function declaration: friend void displayVolume(const Box&
b);.
2. Define ColorBox class (inherits from Box):
a. Private member: std::string color;.
b. Public method: Constructor to set dimensions (passing to Box constructor) and
color.
3. Define displayVolume function (outside classes):
a. Takes const Box& b as argument.
b. Calculates [Link] * [Link] * [Link] (can access private members
due to friend status).
c. Prints the volume.
4. In main function:
a. Create a Box object.
b. Create a ColorBox object.
c. Call displayVolume() for both objects.
Example Input/Output:
Objective:
Implement a base class Account with a balance. Derive SavingsAccount and
CurrentAccount, each with their own method to calculate distinct interest rates. Demonstrate
interest calculation for both types.
110
Steps:
1. Define Account class:
a. Protected member: double balance;.
b. Public methods: Constructor to initialize balance, getBalance().
2. Define SavingsAccount class (inherits from Account):
a. Private member: double savingsInterestRate;.
b. Public methods: Constructor, calculateInterest() (returns balance *
savingsInterestRate).
3. Define CurrentAccount class (inherits from Account):
a. Private member: double currentInterestRate;.
b. Public methods: Constructor, calculateInterest() (returns balance *
currentInterestRate).
4. In main function:
a. Create SavingsAccount and CurrentAccount objects.
b. Set their initial balances and interest rates (via constructors).
c. Call calculateInterest() on each object and print the results.
Example Input/Output:
Savings Account Balance: MK10000.00
Savings Interest: MK200.00
Objective:
Create an abstract base class Media with a pure virtual display() function. Derive Book
and Video from Media, each implementing display() to show their specific details.
Demonstrate the use of abstract classes and pure virtual functions.
Steps:
1. Define Media class:
a. Protected members: string title;.
b. Public constructor: Media(string t).
c. Pure virtual function: virtual void display() = 0;.
d. Virtual Destructor: virtual ~Media() {}.
2. Define Book class (inherits from Media):
a. Private members: string author;, int pages;.
b. Public methods: Constructor, void display() (prints book title, author,
111
pages).
3. Define Video class (inherits from Media):
a. Private members: string director;, int durationMinutes;.
b. Public methods: Constructor, void display() (prints video title,
director, duration).
4. In main function:
a. Create Book and Video objects.
b. Declare Media* pointers and assign Book and Video objects to them.
c. Call display() through the Media* pointers to show polymorphic behavior.
d. Remember to delete dynamically allocated objects.
Example Input/Output:
Objective:
Define two base classes Person (with name, age) and Worker (with workID, salary). Derive
a class Engineer from both Person and Worker. Implement a method to input and display an
engineer's details.
Steps:
1. Define Person class:
a. Protected members: std::string name;, int age;.
b. Public methods: Constructor, inputPersonDetails(),
displayPersonDetails().
2. Define Worker class:
a. Protected members: int workID;, double salary;.
b. Public methods: Constructor, inputWorkerDetails(),
displayWorkerDetails().
3. Define Engineer class (inherits publicly from Person, Worker):
112
a. Public methods:
o Constructor (calls base class constructors if needed).
o inputEngineerDetails(): Calls inputPersonDetails() and
inputWorkerDetails().
o displayEngineerDetails(): Calls displayPersonDetails() and
displayWorkerDetails().
4. In main function:
a. Create an Engineer object.
b. Call inputEngineerDetails() to get data from the user.
c. Call displayEngineerDetails() to show the combined information.
Example Input/Output:
Steps:
1. Define Person class:
a. Protected member: string name;.
b. Public methods: Constructor, setName(), getName().
2. Define Employee class (inherits virtual public Person):
a. Protected member: int employeeID;.
b. Public methods: Constructor (takes ID, calls Person constructor if default-
constructed), setEmployeeID(), getEmployeeID().
3. Define Student class (inherits virtual public Person):
113
a. Protected member: float GPA;.
b. Public methods: Constructor (takes GPA, calls Person constructor if default-
constructed), setGPA(), getGPA().
4. Define WorkingStudent class (inherits public Employee, public Student):
a. Public methods:
o Constructor:
■ Must directly call Person constructor once in its initializer list to
ensure Person is initialized. Also calls Employee and Student
constructors.
o displayDetails():
■ Accesses name (from Person), employeeID (from Employee),
and GPA (from Student).
5. In main function:
a. Create a WorkingStudent object, providing necessary details to its constructor.
b. Call displayDetails() to show the combined information, proving name is
unique.
Example Input/Output:
Objective:
Write a C++ program to implement composition by creating a Result class that contains a
Marks object to calculate and display total marks.
Steps:
1. Define Marks class:
a. Private members: int math, int science.
b. Public members:
o Constructor to initialize marks.
o getTotal() to return total marks.
2. Define Result class:
a. Private members: string studentName, Marks m.
b. Public members:
114
o Constructor to initialize student name and marks.
o displayResult() to print student name and total marks.
3. In main() function:
a. Create a Result object.
b. Call displayResult().
Example Input/Output:
Objective:
Write a C++ program to demonstrate interfaces using an abstract Shape class. Implement the
interface in a Rectangle class to calculate and display area.
Steps:
1. Define an abstract class Shape:
a. Public:
o Pure virtual function calculateArea().
o Pure virtual function display().
2. Define Rectangle class:
a. Private members: int length, int width.
b. Public members:
o Constructor to initialize length and width.
o Implement calculateArea().
o Implement display().
3. In main() function:
a. Create a Shape pointer.
b. Assign it to a Rectangle object.
c. Call display() using the pointer.
Example Input/Output:
Length: 10
Width: 5
Area of Rectangle: 50
115
16.12 Bank Account Interface
Objective:
Write a C++ program to implement interface-based design using an abstract Account class and
a SavingsAccount class.
Steps:
1. Define abstract class Account:
a. Public:
o Pure virtual function calculateInterest().
2. Define SavingsAccount class:
a. Private members: float balance, rate.
b. Public:
o Constructor to initialize balance and rate.
o Implement calculateInterest().
3. In main() function:
a. Create an Account pointer.
b. Assign it to a SavingsAccount object.
c. Call calculateInterest().
Example Input/Output:
Balance: 10000
Interest Rate: 5%
Interest Earned: 500
116
LAB
17 LAB 17: POLYMORPHISM AND ENCAPSULATION
Objective:
Write a C++ program to overload the prefix ++ operator to increment a value by 1 within a custom
class. Create a Count class, initialize its value, then use the overloaded operator to increment and
display the result.
Steps:
1. Define Count class:
a. Private member: int value;.
b. Public members:
o Constructor to initialize value (e.g., to 5).
o Overload operator++() (prefix):
▪ Increment value.
▪ Return *this (reference to the current object).
o display(): Prints the current value.
2. In main function:
a. Create a Count object.
b. Call display() to show the initial value.
c. Use the prefix increment operator: ++myCount;.
d. Call display() again to show the incremented value.
Example Input/Output:
Initial value: 5
Value after prefix increment: 6
Objective:
Write a C++ program to overload the + operator to perform addition of two complex numbers.
Create a Complex class and demonstrate its use.
Steps:
1. Define Complex class:
a. Private members: double real;, double imag;.
b. Public members:
117
o Parameterized constructor to initialize real and imag.
o Overload operator+(const Complex& other):
▪ Create a Complex temporary object.
▪ Set [Link] = this->real + [Link];.
▪ Set [Link] = this->imag + [Link];.
▪ Return temp.
o display(): Prints the complex number in a + bi format.
2. In main function:
a. Create two Complex objects (e.g., c1(2, 3) and c2(1, 4)).
b. Add them using the overloaded + operator:
o Complex c3 = c1 + c2;.
c. Call display() for c1, c2, and c3 to show the addition.
Example Input/Output:
Complex Number 1: 2 + 3i
Complex Number 2: 1 + 4i
Sum: 3 + 7i
Objective:
Implement operator overloading for << (stream insertion operator) to display the values of a
class object. Use this operator to print the details of a Rectangle class with length and
width.
Steps:
1. Define Rectangle class:
a. Private members: float length;, float width;.
b. Public members:
o Parameterized constructor to initialize length and width.
o Declare operator<< as a friend function: friend ostream&
operator<<(ostream& os, const Rectangle& rect);.
2. Define operator<< function (outside the class):
a. Takes ostream& os (output stream) and const Rectangle& rect as
arguments.
b. Insert [Link] and [Link] into os.
c. Return os.
3. In main function:
a. Create a Rectangle object.
b. Print the Rectangle object directly using cout << myRect;.
118
Example Input/Output:
Objective:
Write a C++ program that demonstrates function overloading by creating multiple functions with
the same name (calculateArea) but different parameter lists, to calculate the area of a rectangle,
circle, and triangle.
Steps:
1. Define calculateArea functions:
a. float calculateArea(float length, float width): For rectangle.
b. float calculateArea(float radius): For circle (πr2).
c. float calculateArea(float base, float height, char type) (e.g.,
type to distinguish from rectangle if needed, or use different parameter types if
applicable): For triangle (0.5 * base * height).
2. In main function:
a. Call each calculateArea function with appropriate arguments to demonstrate
overloading.
b. Print the results.
Example Input/Output:
Objective:
Implement a C++ class Complex to represent complex numbers and overload both the + and -
operators to perform addition and subtraction of two complex numbers.
Steps:
1. Define Complex class:
a. Private members: double real;, double imag;.
119
b. Public members:
o Parameterized constructor.
o Overload operator+(const Complex& other): Returns a new Complex
object representing the sum.
o Overload operator-(const Complex& other): Returns a new Complex
object representing the difference.
o display(): Prints the complex number.
2. In main function:
a. Create two Complex objects.
b. Perform addition using + and store in a new object.
c. Perform subtraction using - and store in another new object.
d. Display all complex numbers and results.
Example Input/Output:
Complex Number 1: 5 + 3i
Complex Number 2: 2 + 1i
Sum: 7 + 4i
Difference: 3 + 2i
Objective:
Create a class hierarchy with a base class Person and two derived classes Student and
Teacher. Define a virtual function getRole() in Person and override it in derived classes to
return their specific roles. Demonstrate how a Person pointer can call the overridden function
from derived classes (run-time polymorphism).
Steps:
1. Define Person class:
a. Protected member: string name;.
b. Public members: Constructor, virtual string getRole() const { return
"Person"; }.
c. Virtual destructor: virtual ~Person() {}.
2. Define Student class (inherits from Person):
a. Public members: Constructor, string getRole() const override {
return "Student"; }.
3. Define Teacher class (inherits from Person):
a. Public members: Constructor, string getRole() const override {
return "Teacher"; }.
120
4. In main function:
a. Create Student and Teacher objects.
b. Declare Person* pointers and assign the derived objects to them.
c. Call getRole() through the Person* pointers and print the result.
d. delete dynamically allocated objects.
Example Input/Output:
Alice is a Student
Bob is a Teacher
Objective:
Write a C++ program that demonstrates run-time polymorphism using virtual functions. Create a
base class Shape with a virtual function draw(). Derive Circle and Rectangle, override
draw() in each, and use Shape pointers in main to dynamically invoke the correct draw()
function.
Steps:
1. Define Shape class:
a. Public members: virtual void draw() const = 0; (pure virtual).
b. Virtual destructor: virtual ~Shape() {}.
2. Define Circle class (inherits from Shape):
a. Public members: Constructor, void draw() const override { ... print
"Drawing a Circle" ... }.
3. Define Rectangle class (inherits from Shape):
a. Public members: Constructor, void draw() const override { ... print
"Drawing a Rectangle" ... }.
4. In main function:
a. Create Circle and Rectangle objects dynamically.
b. Declare an array of Shape* pointers.
c. Assign the dynamically created Circle and Rectangle objects to the Shape*
array.
d. Loop through the array and call draw() on each Shape* pointer.
e. delete all dynamically allocated objects.
Example Input/Output:
Drawing a Circle
Drawing a Rectangle
121
17.8 Fuel Efficiency Calculation (Vehicle Hierarchy)
Objective:
Implement a class hierarchy for different vehicle types (e.g., Car, Motorcycle, Truck)
inheriting from a base class Vehicle. Define a virtual function calculateFuelEfficiency()
in the base class and override it in derived classes to provide specific implementations.
Demonstrate how polymorphism allows you to calculate fuel efficiency for different vehicles using
a base class pointer.
Steps:
1. Define Vehicle class:
a. Protected member:
o float fuelConsumptionRate; (e.g., liters per 100km).
b. Public members:
o Constructor, virtual float calculateFuelEfficiency() const
= 0; (pure virtual).
c. Virtual destructor:
o virtual ~Vehicle() {}.
2. Define Car class (inherits from Vehicle):
a. Public members:
o Constructor, float calculateFuelEfficiency() const
override { ... return logic for Car ... }.
3. Define Motorcycle class (inherits from Vehicle):
a. Public members:
o Constructor, float calculateFuelEfficiency() const
override { ... return logic for Motorcycle ... }.
4. Define Truck class (inherits from Vehicle):
a. Public members:
o Constructor, float calculateFuelEfficiency() const
override { ... return logic for Truck ... }.
5. In main function:
a. Create Car, Motorcycle, and Truck objects dynamically.
b. Declare an array of Vehicle* pointers.
c. Assign the derived objects to the Vehicle* array.
d. Loop through the array and call calculateFuelEfficiency() on each
Vehicle* pointer.
e. delete all dynamically allocated objects.
122
Example Input/Output:
Objective:
Create a base class Employee with a virtual function calculateSalary(). Derive
FullTimeEmployee and PartTimeEmployee, overriding calculateSalary() in each to
compute salary based on their types. Demonstrate salary calculation using an array of base class
pointers.
Steps:
1. Define Employee class:
a. Protected members: string name;.
b. Public members: Constructor, virtual double calculateSalary() const
= 0; (pure virtual).
c. Virtual destructor: virtual ~Employee() {}.
2. Define FullTimeEmployee class (inherits from Employee):
a. Private member: double annualSalary;.
b. Public members: Constructor, double calculateSalary() const override
{ return annualSalary; }.
3. Define PartTimeEmployee class (inherits from Employee):
a. Private members: double hourlyRate;, int hoursWorked;.
b. Public members: Constructor, double calculateSalary() const override
{ return hourlyRate * hoursWorked; }.
4. In main function:
a. Create FullTimeEmployee and PartTimeEmployee objects dynamically.
b. Declare an array of Employee* pointers.
c. Assign the derived objects to the Employee* array.
d. Loop through the array and call calculateSalary() on each Employee* pointer.
e. delete all dynamically allocated objects.
Example Input/Output:
123
17.10 Abstract Classes and Pure Virtual Functions (Breathing)
Objective:
Write a C++ program demonstrating abstract classes and pure virtual functions. Create an abstract
base class LivingThing with a pure virtual function breath(). Derive Human and Fish,
implementing breath() in each to describe their breathing mechanism. In main, create objects
of Human and Fish and call breath().
Steps:
1. Define LivingThing class:
a. Public member: virtual void breath() const = 0; (pure virtual).
b. Virtual destructor: virtual ~LivingThing() {}.
2. Define Human class (inherits from LivingThing):
a. Public members: Constructor, void breath() const override { ...
print "Humans breathe with lungs." ... }.
3. Define Fish class (inherits from LivingThing):
a. Public members: Constructor, void breath() const override { ...
print "Fish breathe with gills." ... }.
4. In main function:
a. Create Human and Fish objects dynamically.
b. Call breath() on each object.
c. delete dynamically allocated objects.
Example Input/Output:
Objective:
Implement a C++ class Person encapsulating private attributes name, age, and grade.
Implement public getter and setter methods for these attributes and demonstrate setting and
retrieving values in main.
Steps:
1. Define Person class:
a. Private members: string name;, int age;, float grade;.
124
b. Public methods:
o Setters: setName(string n), setAge(int a), setGrade(float g).
o Getters: getName(), getAge(), getGrade().
o Constructor (optional, but good practice).
2. In main function:
a. Create a Person object.
b. Use setter methods to assign values to its attributes.
c. Use getter methods to retrieve and print the values.
Example Input/Output:
Setting details...
Objective:
Write a C++ class Book encapsulating title, author, and price. Create a function that takes
an array of Book objects and prints the details of the most expensive book, strictly using getter
methods to access private attributes.
Steps:
1. Define Book class:
a. Private members: string title;, string author;, double price;.
b. Public members:
o Parameterized constructor.
o Getters: getTitle(), getAuthor(), getPrice().
o displayDetails() (optional, but convenient).
2. Define findMostExpensiveBook function:
a. Takes const Book books[] and int size as arguments.
b. Initialize int indexOfMostExpensive = 0;.
125
c. Loop from i = 1 to size - 1:
o Compare books[i].getPrice() with
books[indexOfMostExpensive].getPrice().
o If books[i] is more expensive, update indexOfMostExpensive = i;.
d. Print the details of books[indexOfMostExpensive] using its getter methods.
3. In main function:
a. Create an array of Book objects and initialize them with sample data.
b. Call findMostExpensiveBook with the array and its size.
Example Input/Output:
Books available:
Title: Book A, Author: Author X, Price: 250.00
Title: Book B, Author: Author Y, Price: 350.50
Title: Book C, Author: Author Z, Price: 190.99
Objective:
Write a C++ class Company encapsulating companyName, location, and a static data member
totalEmployees. Implement methods to manipulate these values and demonstrate the use of
static members along with instance variables in main.
Steps:
1. Define Company class:
a. Private instance members: string companyName;, string location;.
b. Private static member: static int totalEmployees;.
c. Public members:
o Constructor to initialize companyName and location.
o addEmployee(int count): Increments totalEmployees.
o removeEmployee(int count): Decrements totalEmployees (with check
for non-negative).
o displayCompanyInfo() const: Displays instance members.
o Static method: static void displayTotalEmployees(): Displays
totalEmployees.
2. Initialize static member outside the class: int Company::totalEmployees = 0;.
126
3. In main function:
a. Create Company objects.
b. Call addEmployee() and removeEmployee() on objects to change
totalEmployees.
c. Call displayCompanyInfo() on objects to show instance data.
d. Call Company::displayTotalEmployees() (using class name) to show static
data.
Example Input/Output:
Objective:
Create a C++ class BankAccount with private attributes accountNumber and balance. Allow
only read access to balance via a getter function, but prevent any direct modification of balance
from outside the class. Demonstrate this in main.
Steps:
1. Define BankAccount class:
a. Private members: string accountNumber;, double balance;.
b. Public members:
o Parameterized constructor: BankAccount(string accNum, double
initialBalance): Initializes both.
o Getter for balance: double getBalance() const { return balance; }.
127
o Getter for account number: string getAccountNumber() const {
return accountNumber; }.
o Private setter for balance (or no setter at all): The balance should only change
internally (e.g., via deposit or withdraw methods, if implemented, but not by a
public setBalance method).
2. In main function:
a. Create a BankAccount object.
b. Try to directly access and modify [Link] (this should result in a
compile-time error).
c. Successfully read [Link]().
d. Demonstrate that attempts to modify balance directly will fail.
Example Input/Output:
Objective:
Design a C++ class Flight encapsulating private data members like flightNumber,
destination, departureTime, and seatsAvailable. Implement a reservation system
where seats are reserved through a public method and the number of available seats is updated
accordingly, ensuring it does not go below zero.
Steps:
1. Define Flight class:
a. Private members: std::string flightNumber;, std::string
destination;, std::string departureTime;, int seatsAvailable;.
b. Public members:
o Parameterized constructor to initialize all members, including seatsAvailable.
o getSeatsAvailable() const: Getter for current available seats.
128
o displayFlightInfo() const: Prints all flight details.
o reserveSeats(int numSeats):
■ Checks if numSeats <= seatsAvailable.
■ If yes, seatsAvailable -= numSeats; and return true (success).
■ If no, return false (insufficient seats).
2. In main function:
a. Create a Flight object with an initial number of seats.
b. Display initial flight info.
c. Attempt to reserve a valid number of seats. Print success/failure message and updated
seats.
d. Attempt to reserve more seats than available. Print failure message.
e. Attempt to reserve exactly the remaining seats.
f. Display final flight info.
Example Input/Output:
129
LAB
18 LAB 18: TEMPLATES
Objective:
Write a C++ template function findMax() that takes two arguments of any type and returns the
larger of the two. Test it with both integer and float types in the main() function.
Steps:
1. Define findMax template function:
a. Use template <typename T> before the function signature.
b. Takes two arguments of type T: T arg1, T arg2.
c. Uses a conditional (ternary) operator or if-else to return the larger value.
2. In main function:
a. Call findMax with two int arguments and print the result.
b. Call findMax with two float arguments and print the result.
Example Input/Output:
Max of 5 and 10 is: 10
Max of 3.5 and 2.1 is: 3.5
Objective:
Write a C++ template function swapValues() that swaps the values of two variables of any type.
Test this function using both integer and string types in the main() function.
Steps:
1. Define swapValues template function:
a. Use template <typename T>.
b. Takes two arguments by reference of type T: T& arg1, T& arg2.
c. Use a temporary variable of type T to perform the swap.
2. In main function:
a. Declare two int variables, assign values.
b. Print their initial values.
c. Call swapValues with the int variables.
d. Print their swapped values.
e. Repeat the process for two string variables.
130
Example Input/Output:
Steps:
1. Define min template function:
a. template <typename T> T min(T a, T b): Returns a < b ? a : b;.
2. Define max template function:
a. template <typename T> T max(T a, T b): Returns a > b ? a : b;.
3. In main function:
a. Demonstrate min and max with:
o int values.
o double values.
o char values.
o string values.
b. Print the results for each.
Example Input/Output:
131
18.4 Template Class Pair
Objective:
Create a C++ template class Pair that stores two values of any data type. Include member
functions to get and set these values. Test the class with int, float, and string pairs in the main()
function.
Steps:
1. Define Pair template class:
a. template <typename T1, typename T2> before class Pair.
b. Private members: T1 first;, T2 second;.
c. Public members:
o Constructor to initialize first and second.
o setFirst(T1 val), setSecond(T2 val).
o getFirst() const, getSecond() const.
o display() (optional, but helpful for printing).
2. In main function:
a. Create a Pair<int, int> object, set values, and display.
b. Create a Pair<float, float> object, set values, and display.
c. Create a Pair<std::string, std::string> object, set values, and display.
d. (Optional: Create Pair<int, std::string> for mixed types).
Example Input/Output:
Integer Pair: (10, 20)
Float Pair: (3.14, 2.71)
String Pair: (Hello, World)
Objective:
Write a C++ template function total() that keeps a running total of numeric values entered by
the user and returns the final total. The function should work with any numeric data type.
Demonstrate it in a simple driver program.
Steps:
1. Define total template function:
a. template <typename T> T total()
b. Initialize T sum = 0;.
c. Declare T value;.
d. Use a while loop:
132
o Prompt the user to enter a value (or 0 to quit).
o Read value.
o If value == 0, break the loop.
o Add value to sum.
e. Return sum.
2. In main function:
a. Call total<int>() and print the integer sum.
b. Call total<double>() and print the double sum.
Objective:
Write a C++ function template printArray() that takes an array of any data type and its size,
and prints all elements. Test this function with arrays of integers and floats.
Steps:
1. Define printArray template function:
a. template <typename T> void printArray(const T arr[], int size)
b. Use a for loop to iterate from 0 to size - 1.
c. Print arr[i] followed by a space.
d. Print a newline character after the loop.
2. In main function:
a. Declare an int array and initialize it.
b. Call printArray with the int array.
c. Declare a float array and initialize it.
d. Call printArray with the float array.
133
Example Input/Output:
Integer array: 1 2 3 4 5
Float array: 1.1 2.2 3.3 4.4
Objective:
Write a C++ template function that accepts an argument of any numeric type and returns its
absolute value. Test the template in a simple driver program.
Steps:
1. Define absoluteValue template function:
a. template <typename T> T absoluteValue(T val)
b. Use if (val < 0) { return -val; } else { return val; } or
return (val < 0) ? -val : val;.
2. In main function:
a. Test with a negative integer.
b. Test with a positive integer.
c. Test with a negative float/double.
d. Test with a positive float/double.
e. Print results for each.
Example Input/Output:
Objective:
Write a C++ template function sortArray() that sorts an array of any data type in ascending
order using Bubble Sort. Test this function with arrays of int and float types in the main()
function.
134
Steps:
1. Define sortArray template function:
a. template <typename T> void sortArray(T arr[], int size)
b. Implement Bubble Sort logic:
o Outer loop from i = 0 to size - 2.
o Inner loop from j = 0 to size - 1 - i.
o If arr[j] > arr[j + 1], swap arr[j] and arr[j + 1] using a
temporary variable of type T.
2. In main function:
a. Declare an int array, initialize it with unsorted values.
b. Print the original int array.
c. Call sortArray with the int array.
d. Print the sorted int array.
e. Repeat the process for a float array.
Example Input/Output:
Objective:
Write a C++ template function findMinMax() that takes an array of any data type and its size,
and returns both the minimum and maximum values found in the array. Test this function with
arrays of integers and floats.
Clarification:
To return both, you can pass two reference parameters to the function (e.g., T& minVal, T&
maxVal), or return a pair<T, T>. For simplicity, use reference parameters.
Steps:
1. Define findMinMax template function:
a. template <typename T> void findMinMax(const T arr[], int size,
T& minVal, T& maxVal)
b. Handle empty array case (optional).
c. Initialize minVal = arr[0]; and maxVal = arr[0];.
135
d. Loop from i = 1 to size - 1:
o If arr[i] < minVal, update minVal = arr[i];.
o If arr[i] > maxVal, update maxVal = arr[i];.
2. In main function:
a. Declare an int array.
b. Declare int minInt, maxInt;.
c. Call findMinMax with the int array, minInt, and maxInt.
d. Print minInt and maxInt.
e. Repeat for a float array and float minFloat, maxFloat;.
Example Input/Output:
Integer array: 10 3 25 7 1
Min: 1, Max: 25
Objective:
Write a C++ program to demonstrate argument deduction by displaying elements of an array
using a template function.
Steps:
Example Input/Output:
Array elements: 1 2 3 4 5
136
18.11 Template Function for Absolute Value
Objective:
Write a C++ program to show argument deduction by calculating the absolute value of a
number using a template function.
Steps:
Example Input/Output:
Objective:
Create a C++ template function isEqual() that checks if two variables are equal. Write a
template specialization for the char type that ignores case when comparing characters. Test this
function with int, float, and char types.
Steps:
1. Define general isEqual template function:
a. template <typename T> bool isEqual(T a, T b) { return a == b;
}.
2. Define template specialization for char:
a. template <> bool isEqual<char>(char a, char b) { return
tolower(a) == tolower(b); }.
3. In main function:
a. Test general isEqual with int values (equal and unequal).
b. Test general isEqual with float values (equal and unequal).
137
c. Test isEqual with char values:
o Same case, equal.
o Different case, equal (e.g., 'A' and 'a').
o Different characters.
d. Print results for each.
Example Input/Output:
Objective:
Write a C++ template function compareThree() that takes three parameters of any data type and
returns the largest one. Test this function with int, float, and double types.
Steps:
1. Define compareThree template function:
a. template <typename T> T compareThree(T a, T b, T c)
b. Use nested conditional (ternary) operators or if-else statements to find the largest
among a, b, and c.
c. Return the largest value.
2. In main function:
a. Call compareThree with int arguments and print the result.
b. Call compareThree with float arguments and print the result.
c. Call compareThree with double arguments and print the result.
Example Input/Output:
138
18.14 Template Class Matrix
Objective:
Create a C++ template class Matrix that represents a 2D matrix with rows and columns.
Implement functions for addition and subtraction of matrices. Test the class with int matrices in
the main() function.
Clarification:
This requires dynamic allocation for the matrix data within the class. Remember rule of three/five
(destructor, copy constructor, assignment operator) for classes with dynamic memory, but for
brevity, focus on the core functionality.
Steps:
1. Define Matrix template class:
a. template <typename T> before class Matrix.
b. Private members: int rows;, int cols;, T** data; (pointer to pointers
for 2D array).
c. Public members:
o Constructor: Matrix(int r, int c): Allocates data (2D array new
T*[rows], then new T[cols] for each row). Initializes elements (e.g., to 0).
o Destructor: ~Matrix(): Deallocates memory (delete[] data[i] for
each row, then delete[] data).
o setElement(int r, int c, T val): Sets value at data[r][c].
o getElement(int r, int c) const: Returns value at data[r][c].
o Overload operator+(const Matrix& other):
▪ Check for compatible dimensions.
▪ Create a new Matrix (result).
▪ Loop through elements, add corresponding values:
[Link][i][j] = this->data[i][j] +
[Link][i][j];.
▪ Return result.
o Overload operator-(const Matrix& other): (Similar to addition).
o display() const: Prints the matrix.
2. In main function:
a. Create two Matrix<int> objects, initialize them with some values.
b. Display Matrix1 and Matrix2.
c. Perform addition: Matrix<int> sumMatrix = matrix1 + matrix2;.
d. Display Sum Matrix.
e. Perform subtraction: Matrix<int> diffMatrix = matrix1 - matrix2;.
f. Display Difference Matrix.
139
Example Input/Output:
Matrix 1:
1 2
3 4
Matrix 2:
5 6
7 8
Sum Matrix:
6 8
10 12
Difference Matrix:
-4 -4
-4 -4
140
LAB
19 LAB 19: FILE HANDLING
Objective:
Write a C++ program to prompt the user for classmate details (First Name, Surname, Age,
District, Phone Number) and save them to a file named "[Link]". The program
should append new information to the file on subsequent runs.
Steps:
1. Open a file named "[Link]" in append mode (ios::app).
2. Prompt the user to enter First Name, Surname, Age, District, and Phone Number.
3. Read each detail, using getline for names and district to handle spaces.
4. Write all entered details to the file, separating them with commas (CSV format) and
adding a newline after each classmate's record.
5. Close the file.
Example Input/Output:
141
19.2 Read Classmate Information from File
Objective:
Write a C++ program that reads the classmate information from the "[Link]" file
(created in the previous program) and prints it on the screen.
Steps:
1. Open the file named "[Link]" in read mode (ios::in).
2. Check if the file was opened successfully. If not, print an error message and exit.
3. Read the file line by line using getline().
4. For each line, parse the comma-separated values. A stringstream can be used to easily
extract values separated by a delimiter.
5. Print each classmate's details in a formatted way.
6. Close the file.
Example Input/Output:
Objective:
Write a C++ program to count the number of vowels (a, e, i, o, u, case-insensitive) present
in a text file named "[Link]".
142
Steps:
1. Create a "[Link]" file with some sample text.
2. Open "[Link]" in read mode.
3. Initialize a vowelCount variable to 0.
4. Read the file character by character using a while loop and
[Link](char_variable).
5. Convert each character to lowercase using tolower().
6. Check if the lowercase character is a vowel. If it is, increment vowelCount.
7. Print the total vowelCount after reading the entire file.
8. Close the file.
Example Input/Output:
Objective:
Write a C++ program that reads a text file and counts the total number of words in the file.
Steps:
1. Create a text file (e.g., "[Link]") with some sample content.
2. Open the file in read mode.
3. Initialize a wordCount variable to 0.
4. Use a while loop and the extraction operator >> to read words one by one. The >>
operator automatically skips whitespace and reads until the next whitespace.
5. Increment wordCount for each word successfully read.
6. Print the total wordCount.
7. Close the file.
Example Input/Output:
Input (from [Link]):
This is a sample file.
It has some words.
143
19.5 Copy File Content
Objective:
Develop a C++ program that copies the content of a file named "[Link]" to another file
named "[Link]".
Steps:
1. Create "[Link]" with some sample content.
2. Open "[Link]" in read mode.
3. Open "[Link]" in write mode (will create/overwrite).
4. Check if both files were opened successfully.
5. Read "[Link]" line by line using getline().
6. Write each line read from "[Link]" to "[Link]".
7. Close both files.
Example Input/Output:
Objective:
Write a function file_copy() that copies the content of one file to another, accepting ifstream
and ofstream objects as parameters, using a loop to read and write line by line without rdbuf().
Demonstrate its usage.
Steps:
1. Define the file_copy function that takes ifstream& source and ofstream&
destination as arguments.
2. Inside file_copy, read lines from source using getline() and write them to
destination.
3. In main, create "[Link]" and open it for reading.
144
4. Open "[Link]" for writing.
5. Call file_copy with the opened file streams.
6. Close both files in main.
Example Input/Output:
Objective:
Create a C++ program that writes an array of integers to a binary file and then reads it back from
the file, displaying the read values.
Steps:
1. Define an integer array.
2. Write to binary file:
a. Open "[Link]" in binary output mode (ios::out | ios::binary).
b. Use [Link](reinterpret_cast<char*>(array_name),
size_in_bytes); to write the entire array.
3. Read from binary file:
a. Open "[Link]" in binary input mode (ios::in | ios::binary).
b. Define a new array (or use a buffer) to store read data.
c. Use [Link](reinterpret_cast<char*>(new_array_name),
size_in_bytes); to read data back.
4. Print the elements of the array that was read from the file.
5. Close both files.
Example Input/Output:
145
19.8 Display Lines Starting with 'M' or 'N'
Objective:
Write a C++ program to read the content of a text file "[Link]" and display all lines that start
with either 'M' or 'N' (case-insensitive).
Steps:
1. Create a "[Link]" file with lines, some starting with 'M' or 'N'.
2. Open "[Link]" in read mode.
3. Read the file line by line using getline().
4. For each line, check if the line is not empty and its first character (converted to uppercase
for case-insensitivity) is 'M' or 'N'.
5. If the condition is met, print the entire line.
6. Close the file.
Example Input/Output:
Objective:
Write a C++ program that reads a text file named "[Link]" line by line and counts the total
number of lines in the file, then prints the total count.
Steps:
1. Create a "[Link]" file with some multi-line content.
2. Open "[Link]" in read mode.
3. Initialize lineCount to 0.
4. Read the file line by line using getline() in a while loop.
146
5. Increment lineCount for each line read.
6. Print the lineCount.
7. Close the file.
Example Input/Output:
Objective:
Write a C++ program that reads an array of integers from a binary file named "[Link]" and
writes them to a new binary file named "[Link]".
Steps:
1. First, ensure "[Link]" exists and has some integer data (e.g., from problem 9.7).
2. Open "[Link]" for reading in binary mode (ios::in | ios::binary).
3. Open "[Link]" for writing in binary mode (ios::out | ios::binary).
4. Check if both files were opened successfully.
5. Determine the size of "[Link]" (to know how many integers to read).
6. Read integers from "[Link]" in chunks or one by one. For simplicity, read into a
buffer.
7. Write the read integers from the buffer to "[Link]".
8. Close both files.
Example Input/Output:
147
19.11 Calculate Average Score from Student Records File
Objective:
Write a C++ program that reads student records (name and score per record) from a file named
"[Link]", calculates, and displays the average score of all students.
Steps:
1. Create a "[Link]" file with sample student names and scores (e.g., "Alice
85", "Bob 90").
2. Open "[Link]" in read mode.
3. Initialize totalScore = 0.0 and studentCount = 0.
4. Read the file, extracting name (string) and score (float) for each record.
5. Add the score to totalScore and increment studentCount.
6. After reading all records, calculate averageScore = totalScore / studentCount.
7. Print the average score. Handle the case of no students.
8. Close the file.
Example Input/Output:
148
19.12 Sum and Average from File to File
Objective:
Write a C++ program that reads a list of numbers from a file named "[Link]", calculates
their sum and average, and writes these results to another file named "[Link]".
Steps:
1. Create "[Link]" with one number per line or space-separated numbers.
2. Open "[Link]" for reading.
3. Open "[Link]" for writing.
4. Check if both files opened successfully.
5. Initialize sum = 0.0 and count = 0.
6. Read numbers from "[Link]" one by one using the extraction operator >>.
7. Add each number to sum and increment count.
8. After reading, calculate average = sum / count.
9. Write the sum and average to "[Link]".
10. Close both files.
Example Input/Output:
149
19.13 Search Word in Text File and Count Occurrences
Objective:
Write a C++ program that prompts the user for a filename and a word to search for, then reads the
specified text file and counts all occurrences of that word.
Steps:
1. Prompt the user for the filename.
2. Prompt the user for the word to search for.
3. Open the specified file in read mode.
4. Check if the file opened successfully.
5. Initialize wordCount = 0.
6. Read words from the file one by one using the extraction operator >>.
7. For each word read, compare it to the searchWord.
8. If they match, increment wordCount.
9. Print the total occurrences.
10. Close the file.
Example Input/Output:
Input:
Enter filename: [Link]
Enter word to search: the
Objective:
Write a C++ program that demonstrates how to write student records (name and ID) to a file named
"students_records.txt" and then read the records back from the same file and display them
on the screen.
150
Steps:
1. Write Records:
a. Open "students_records.txt" in write mode (ios::out).
b. Prompt the user for the number of students.
c. Loop n times:
■ Prompt for student name and ID.
■ Write name and id to the file, each on a new line or formatted.
2. Read Records:
a. Close the output file.
b. Open "students_records.txt" in read mode (ios::in).
c. Read student name (string) and id (int) from the file using the extraction
operator >>.
d. Print each student's details.
e. Close the input file.
Example Input/Output:
Input:
Enter number of students: 2
Enter student 1 name: Chris
Enter student 1 ID: 111
Enter student 2 name: Dana
Enter student 2 ID: 222
Objective:
Write a C++ program that reads lines from a file, sorts them in alphabetical order without using
vector or sort from the STL, and writes the sorted lines back to a new file.
Steps:
1. Define a constant MAX_LINES and MAX_LINE_LENGTH for a fixed-size dynamic array
approach to keep the solution simpler given the constraints.
151
2. Read Lines:
a. Open "[Link]" for reading.
b. Dynamically allocate an array of char* (e.g., char** lines).
c. Loop to read each line using getline() into a std::string buffer.
d. For each line read, dynamically allocate a char[] of sufficient size
(MAX_LINE_LENGTH) and copy the string content into it using strcpy. Store the
char* in the lines array. Keep track of numLines.
3. Sort Lines (Bubble Sort on char* array):
a. Implement Bubble Sort to sort the lines array (array of char* pointers).
b. Use strcmp() to compare C-strings.
c. Swap the char* pointers in the lines array if they are in the wrong order.
4. Write Sorted Lines:
a. Open "[Link]" for writing.
b. Loop through the sorted lines array and write each char* (line) to
"[Link]".
5. Memory Management:
a. After writing, loop through the lines array and delete[] each char[]
(individual line memory).
b. Finally, delete[] lines; (delete the array of pointers).
c. Close all files.
Example Input/Output:
Objective:
Create a C++ program that checks if a specified file exists, and if it has read and write
permissions (as indicated by successful opening in respective modes).
152
Steps:
1. Prompt the user for the filename.
2. Check Existence:
a. Attempt to open the file with ifstream. If is_open() is true, it exists. Close
it.
3. Check Readability:
a. Attempt to open the file with ifstream. If is_open() is true, it's readable.
Close it.
4. Check Writability:
a. Attempt to open the file with ofstream.
o If is_open() is true, it's writable. (Note: ofstream creates a file if it
doesn't exist, which can make "writability" seem always true. A
more robust check might involve OS-specific calls, but for C++ streams,
successful ofstream opening implies writability.) Close it.
5. Print the results for each check.
Input:
Enter filename: existing_file.txt
Output:
File 'existing_file.txt' exists.
File 'existing_file.txt' is readable.
File 'existing_file.txt' is writable.
Input:
Enter filename: non_existent.txt
Output:
File 'non_existent.txt' does NOT exist.
File 'non_existent.txt' is NOT readable.
File 'non_existent.txt' is writable. (Note: it might create
it)
153
19.17 Open File for Reading with Error Handling
Objective:
Write a C++ program that attempts to open a file for reading. If the file does not exist or cannot
be opened, the program should print an error message and exit gracefully.
Steps:
1. Prompt the user for the filename.
2. Declare an ifstream object.
3. Attempt to open the file using the filename.
4. Check if the file was opened successfully using inFile.is_open().
5. If not successful, print an error message indicating failure to open and return 1 from main.
6. If successful, print a success message, then close the file and return 0 from main.
Input:
Enter filename: non_existent_file.txt
Output:
Error: Could not open non_existent_file.txt for reading.
Exiting program
Input:
Enter filename: existent_file.txt
Output:
Successfully opened existent_file.txt for reading.
154
19.18 Read CSV File and Print Rows
Objective:
Write a C++ program that reads a CSV file named "[Link]" line by line, splits each line into
fields based on the comma delimiter, and prints each field to the console.
Steps:
1. Create a "[Link]" file with comma-separated values (e.g.,
Name,Age,City\nAlice,25,NY).
2. Open "[Link]" for reading.
3. Check if the file was opened successfully.
4. Read the file line by line using getline().
5. For each line:
a. Use a stringstream to process the line.
b. Use getline(stringstream, field, ',') in a loop to extract fields
separated by commas.
c. Print each extracted field.
d. Print a newline after each row's fields.
6. Close the file.
Example Input/Output:
155
19.19 Replace Word in Text File and Save to New File
Objective:
Write a C++ program that reads a text file named "[Link]", replaces all occurrences of a
specified word with another word, and saves the modified text to a new file named
"modified_document.txt".
Steps:
1. Create a "[Link]" file with some content.
2. Prompt the user for the word to find and the word to replace it with.
3. Open "[Link]" for reading.
4. Check if the file opened successfully.
5. Read the entire content of "[Link]" into a string. (This is simpler for
replacement logic).
6. Use a while loop with find() and replace() to replace all occurrences of the target
word.
7. Open "modified_document.txt" for writing (creates/overwrites).
8. Check if the output file opened successfully.
9. Write the modified string to "modified_document.txt".
10. Close both files.
Example Input/Output:
156