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

Lab Guide - Programming II - CIS-PRO-122

This document is a lab guide for Programming II (CIS-PRO-122) at the School of Science and Technology, detailing structured approaches to C++ programming problems. It includes tips for success, a comprehensive table of contents covering various programming concepts such as arrays, pointers, structures, strings, classes, inheritance, polymorphism, templates, and file handling. The guide emphasizes academic use and prohibits commercial distribution.

Uploaded by

mpombezafrank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views112 pages

Lab Guide - Programming II - CIS-PRO-122

This document is a lab guide for Programming II (CIS-PRO-122) at the School of Science and Technology, detailing structured approaches to C++ programming problems. It includes tips for success, a comprehensive table of contents covering various programming concepts such as arrays, pointers, structures, strings, classes, inheritance, polymorphism, templates, and file handling. The guide emphasizes academic use and prohibits commercial distribution.

Uploaded by

mpombezafrank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

SCHOOL OF SCIENCE AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION


SYSTEMS

Bachelor of Science in Management Information Systems


Bachelor of Science in Information Technology
[BIS/BIT]
Year 1

SEMESTER TWO

PROGRAMMING II
(CIS-PRO-122)
Lab Guide

Developed by
Michael R Chinguwo

: +265 (0) 993 195 721 :[email protected]


DISCLAIMER
This document is intended solely for academic purposes and to support teaching and learning. Any
use for economic or commercial purposes is strictly prohibited. Users are not permitted to
distribute, share, or disseminate the content, and its use is limited to the advancement of individual
knowledge.

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.

Tips for Success in C++ Programming Lab Practice


1. Before the Lab
a. Understand the Concepts
• Review topics like loops, arrays, functions, and classes.
b. Practice Basic Syntax
• Know how to declare variables, use control structures, and write simple functions.
c. Prepare a Cheat Sheet
• Include syntax for if, for, while, functions, and class definitions.
d. Plan Using IPO Model
• Identify: Input: What data is needed? Processing: What logic is applied?
Output: What result is shown?

2. During the Lab


a. Start Simple
• Begin with a basic working version, then build on it.
b. Break Down the Problem
• Work step by step: write and test small parts of the program.
c. Use Comments
• Explain your logic with comments to make debugging easier.
d. Avoid Common Errors
• Watch out for: Missing; (semicolons), unmatched {} (braces), forgetting
#include <iostream> or using namespace std;
e. Test Thoroughly
• Try different inputs (e.g., 0, negative values, edge cases).
f. Ask for Help if Stuck
• Don’t spend more than 10 minutes on one issue without seeking help.
g. Format your code properly
• Use indentation
h. Compile and test frequently as you build your code

3. After the Lab


a. Revisit and Rewrite
• Re-type the program from memory at home to strengthen learning.
b. Modify and Extend
• Add new features or try solving the same problem in a different way.
c. Organize Your Code
• Save files in labeled folders like: Arrays, OOP, FileHandling, etc.

iii
TABLE OF CONTENTS

LAB 1: ARRAYS ........................................................................................................................... 1


1.1 Initialize and Print Array Elements ................................................................................. 1
1.2 Store and Display User Inputs in an Array ..................................................................... 1
1.3 Sum and Average of Array Elements .............................................................................. 2
1.4 Find Highest and Lowest in Array .................................................................................. 2
1.5 Array Analysis: Frequency, Above, and Below a Given Number .................................. 3
1.6 Linear Search in an Array ............................................................................................... 4
1.7 Selection Sort an Array ................................................................................................... 5
1.8 Count Frequency of Each Element in Array ................................................................... 5
1.9 Reverse Array Elements .................................................................................................. 6
1.10 Find Duplicate Elements in Array................................................................................... 7
1.11 Find Unique Elements in Array ...................................................................................... 8
1.12 Student Grades and Averages in Table Format ............................................................... 8
1.13 Add Two 3x3 Matrices .................................................................................................... 9
1.14 Add Two 3x3 Matrices .................................................................................................. 10
LAB 2: POINTERS..................................................................................................................... 12
2.1 Declare and Use an Integer Pointer .............................................................................. 12
2.2 Increment Value of Variable Using Pointer................................................................... 12
2.3 Iterate Through Array with Pointer ............................................................................... 13
2.4 Function to Sum Array Elements Using Pointer ........................................................... 13
2.5 Function to Swap Two Integers Using Pointers ............................................................ 14
2.6 Function to Return Pointer to Maximum Element in Array ......................................... 15
2.7 Sort Array Using Pointer Arithmetic (Bubble Sort) ...................................................... 15
2.8 Dynamically Allocate, Use, and Free Single Integer Memory ..................................... 16
2.9 Dynamically Allocate, Populate, Print, and Free Array Memory ................................. 17
2.10 Pointer to a Function as an Argument ........................................................................... 17
2.11 C-String to Uppercase Using Pointer Arithmetic.......................................................... 18
2.12 Dynamically Allocated Test Scores: Sort and Average ................................................. 19
2.13 Function to Determine Median of a Sorted Array (Pointer Notation) .......................... 20

iv
2.14 Statistical Data for Movies: Average, Median, Mode (Dynamic Allocation, Pointer
Notation).................................................................................................................................... 21
LAB 3: STRUCTURES .............................................................................................................. 23
3.1 Student Structure Declaration and Printing .................................................................. 23
3.2 Book Structure Initialization and Printing .................................................................... 23
3.3 Customer Structure Declaration and Initialization (Fixed Values) ............................... 24
3.4 Customer Structure - User Input ................................................................................... 24
3.5 Customer Structure Array - User Input ......................................................................... 25
3.6 Employee Structure Array Iteration .............................................................................. 27
3.7 Car Structure with Pointers and Update Function ........................................................ 28
3.8 Nested Employee Structure........................................................................................... 29
3.9 Rectangle Structure: Area Calculation and Dimension Update by Reference .............. 29
3.10 Savings Account Structure with Menu ......................................................................... 30
3.11 Company Division Sales Data ...................................................................................... 32
3.12 Monthly Budget Tracking ............................................................................................. 34
LAB 4: STRINGS MANIPULATION ...................................................................................... 36
4.1 Character to Character Code ......................................................................................... 36
4.2 Print Character Multiple Times..................................................................................... 36
4.3 Length of Text from Keyboard ..................................................................................... 37
4.4 Compare Two Words Lexicographically....................................................................... 37
4.5 String Length Using Character Array and Loop ........................................................... 38
4.6 Access and Modify Third Character in String .............................................................. 38
4.7 Reverse String Function (In Place) ............................................................................... 39
4.8 String Length Function (Without strlen) ....................................................................... 39
4.9 Count Vowels and Consonants in String ....................................................................... 40
4.10 Check if String is Palindrome ....................................................................................... 41
4.11 Concatenate Two Strings Function ............................................................................... 42
4.12 Count Words in a Sentence ........................................................................................... 42
4.13 Convert String to Uppercase (Without Built-in) ........................................................... 43
4.14 Function to Count Words in C-String ........................................................................... 43
4.15 Sort 10 Strings Alphabetically (Using Pointers) ........................................................... 44
4.16 Dynamically Allocated 2D String Array with Operations ............................................ 45
4.17 Capitalize First Character of Each Sentence ................................................................. 47

v
4.18 Password Validation Program ....................................................................................... 48
LAB 5: CLASSES AND OBJECTS .......................................................................................... 49
5.1 Rectangle Class Definition ........................................................................................... 49
5.2 Circle Class with Constructor and Area Calculation .................................................... 49
5.3 Student Class with Parameterized Constructor ............................................................. 50
5.4 Book Class with Default Constructor and Destructor................................................... 51
5.5 Point Class with Copy Constructor ............................................................................... 52
5.6 Employee Class Array with User Input ........................................................................ 53
5.7 Date Class with Three-Parameter Default Constructor and Formats ............................ 54
5.8 Phone Manufacturing Plant Class ................................................................................. 56
LAB 6: INHERITANCE............................................................................................................. 58
6.1 Inheritance: Person and Student Classes....................................................................... 58
6.2 Polymorphism: Shape, Rectangle, and Circle............................................................... 58
6.3 Inheritance with Parameterized Constructor (Base Class Call) .................................... 59
6.4 Protected Members Inheritance .................................................................................... 60
6.5 Friend Function with Inheritance (Box and ColorBox) ................................................ 61
6.6 Inheritance for Account Types (Interest Calculation) ................................................... 61
6.7 Abstract Base Class with Pure Virtual Function ........................................................... 62
6.8 Multiple Inheritance: Person, Worker, and Engineer .................................................... 63
6.9 Virtual Inheritance: Person, Employee, Student, WorkingStudent ............................... 64
LAB 7: POLYMORPHISM AND ENCAPSULATION........................................................... 66
7.1 Overload Prefix Increment (++) Operator .................................................................... 66
7.2 Overload Addition (+) Operator for Complex Numbers............................................... 66
7.3 Overload Stream Insertion (<<) Operator ..................................................................... 67
7.4 Function Overloading Example (Area Calculation) ..................................................... 68
7.5 Overload + and - Operators for Complex Numbers...................................................... 68
7.6 Virtual Function getRole() with Inheritance ................................................................. 69
7.7 Run-Time Polymorphism with draw() Function ........................................................... 70
7.8 Fuel Efficiency Calculation (Vehicle Hierarchy) .......................................................... 71
7.9 Calculate Salary (Employee Hierarchy) ....................................................................... 72
7.10 Abstract Classes and Pure Virtual Functions (Breathing) ............................................. 73
7.11 Person Class with Getters and Setters ........................................................................... 73

vi
7.12 Most Expensive Book Finder (Using Getters) .............................................................. 74
7.13 Company Class with Static Data Member .................................................................... 75
7.14 BankAccount Class with Read-Only Balance .............................................................. 76
7.15 Flight Reservation System Class .................................................................................. 77
LAB 8: TEMPLATES................................................................................................................. 79
8.1 Template Function findMax() ....................................................................................... 79
8.2 Template Function swapValues() .................................................................................. 79
8.3 Templates for min() and max() Functions .................................................................... 80
8.4 Template Class Pair....................................................................................................... 81
8.5 Template Function total() for Running Sum ................................................................. 81
8.6 Template Function printArray() .................................................................................... 82
8.7 Template Function for Absolute Value.......................................................................... 83
8.8 Template Function sortArray() using Bubble Sort........................................................ 83
8.9 Template Function findMinMax() for Array ................................................................. 84
8.10 Template Function isEqual() with char Specialization ................................................. 85
8.11 Template Function compareThree() .............................................................................. 86
8.12 Template Class Matrix .................................................................................................. 87
LAB 9: FILE HANDLING ......................................................................................................... 89
9.1 Save Classmate Details to File...................................................................................... 89
9.2 Read Classmate Information from File ......................................................................... 90
9.3 Count Vowels in a Text File .......................................................................................... 90
9.4 Count Words in a Text File ........................................................................................... 91
9.5 Copy File Content ......................................................................................................... 92
9.6 File Copy Function (without rdbuf()) ........................................................................... 92
9.7 Read/Write Array of Integers to Binary File ................................................................. 93
9.8 Display Lines Starting with 'M' or 'N' ........................................................................... 94
9.9 Count Lines in a Text File ............................................................................................. 94
9.10 Copy Integers from Binary File to another Binary File ................................................ 95
9.11 Calculate Average Score from Student Records File .................................................... 96
9.12 Sum and Average from File to File ............................................................................... 97
9.13 Search Word in Text File and Count Occurrences ........................................................ 98
9.14 Write and Read Student Records to/from File .............................................................. 98

vii
9.15 Sort Lines in a File and Write to New File ................................................................... 99
9.16 Check File Existence, Readability, and Writability .................................................... 100
9.17 Open File for Reading with Error Handling ............................................................... 102
9.18 Read CSV File and Print Rows ................................................................................... 103
9.19 Replace Word in Text File and Save to New File ....................................................... 104

viii
LAB
1 LAB 1: ARRAYS

1.1 Initialize and Print Array Elements

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

1.2 Store and Display User Inputs in an Array

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

1
1.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

1.4 Find Highest and Lowest in Array

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.

2
Example Input/Output:

Enter 10 integers: 15 8 23 4 30 12 6 19 2 27

Highest: 30
Lowest: 2

1.5 Array Analysis: Frequency, Above, and Below a Given


Number

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

The number 10 appears 3 times.


Numbers above 10: 12
Numbers below 10: 5 3 7 1 8 6

3
1.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:

Enter the number of elements: 5


Enter elements:10 20 30 40 50

Enter value to search: 30

Value 30 found at index 2.

Enter the number of elements: 4


Enter elements:1 2 3 4

Enter value to search: 5

Value 5 not found in the array.

4
1.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:

Enter the number of elements: 5


Enter elements:64 25 12 22 11

Sorted array: 11 12 22 25 64

1.8 Count Frequency of Each Element 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. Count the frequency of each element in the array and print the frequency
count.

5
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:

Enter the number of elements: 7


Enter elements:10 20 10 30 20 10 40

Element 10: 3 times


Element 20: 2 times
Element 30: 1 time
Element 40: 1 time

1.9 Reverse Array Elements

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.

6
Example Input/Output:
Enter the number of elements: 5
Enter elements:1 2 3 4 5

Reversed array: 5 4 3 2 1

1.10 Find Duplicate 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 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:

Enter the number of elements: 7


Enter elements: 10 20 10 30 20 10 40

Duplicate elements: 10 20 10

7
1.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:

Enter the number of elements: 7


Enter elements:10 20 10 30 20 10 40

Unique elements: 30 40

1.12 Student Grades and Averages in Table Format

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.

8
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:

Enter grades for Student 1 (6 grades): 85 90 78 92 88 95


Enter grades for Student 2 (6 grades): 70 65 80 75 72 68
Enter grades for Student 3 (6 grades): 95 98 90 92 96 94
Enter grades for Student 4 (6 grades): 60 55 62 58 65 61
Enter grades for Student 5 (6 grades): 80 82 85 79 81 83

Student | Grade 1 | Grade 2 |Grade 3 | Grade 4| Grade 5 | Grade 6 | Average


---------------------------------------------------------------------------
1 | 85 | 90 | 78 | 92 | 88 | 95 | 88.00
2 | 70 | 65 | 80 | 75 | 72 | 68 | 71.67
3 | 95 | 98 | 90 | 92 | 96 | 94 | 94.17
4 | 60 | 55 | 62 | 58 | 65 | 61 | 60.17
5 | 80 | 82 | 85 | 79 | 81 | 83 | 81.67

Highest Average: 94.17


Lowest Average: 60.17

1.13 Add Two 3x3 Matrices

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.

9
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:

Enter elements for Matrix 1 (3x3):


1 2 3
4 5 6
7 8 9

Enter elements for Matrix 2 (3x3):


9 8 7
6 5 4
3 2 1

Resultant Matrix (Matrix1 + Matrix2):


10 10 10
10 10 10
10 10 10

1.14 Add Two 3x3 Matrices

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.

10
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:

Enter elements for Matrix 1 (3x3):


1 2 3
4 5 6
7 8 9

Enter elements for Matrix 2 (3x3):


9 8 7
6 5 4
3 2 1

Resultant Matrix (Matrix1 * Matrix2):


30 24 18
84 69 54
138 114 90

11
LAB
2 LAB 2: POINTERS

2.1 Declare and Use an Integer Pointer

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:

Value of original variable: 123

Address stored in pointer: 0x7ffee5a1b0ac (This address will


vary)

Value accessed via pointer: 123

2.2 Increment Value of Variable Using Pointer

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.

12
Example Input/Output:

Original value: 10
Value after increment using pointer: 11

2.3 Iterate Through Array with Pointer

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

2.4 Function to Sum Array Elements Using Pointer

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.

13
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

2.5 Function to Swap Two Integers Using Pointers

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:

Before swap: num1 = 10, num2 = 20


After swap: num1 = 20, num2 = 10

14
2.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:

Maximum value in the array: 45

2.7 Sort Array Using Pointer Arithmetic (Bubble Sort)

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:

15
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
1.
Sorted
2. array: 11 12 22 25 64

2.8 Dynamically Allocate, Use, and Free Single Integer Memory

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:

Value of dynamically allocated integer: 75

16
2.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 the number of elements: 4

Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40

Array elements: 10 20 30 40
Memory freed.

2.10 Pointer to a Function as an Argument

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.

17
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

2.11 C-String to Uppercase Using Pointer Arithmetic

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.

18
Example Input/Output:
Enter a string: Hello World!
Uppercase string: HELLO WORLD!

2.12 Dynamically Allocated Test Scores: Sort and Average

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;.

19
Example Input/Output:

Enter the number of test scores: 5


Enter score 1: 85.5
Enter score 2: 92.0
Enter score 3: 78.5
Enter score 4: 90.0
Enter score 5: 88.0

Sorted Test Scores:78.5 85.5 88.0 90.0 92.0


Average Score: 86.80

2.13 Function to Determine Median of a Sorted Array (Pointer


Notation)

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

Array (even size): 10 20 30 40 50 60


Median: 35.00

20
2.14 Statistical Data for Movies: Average, Median, Mode
(Dynamic Allocation, Pointer Notation)

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

21
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:

Enter the number of students surveyed: 7


Enter movies seen by student 1: 3
Enter movies seen by student 2: 1
Enter movies seen by student 3: 4
Enter movies seen by student 4: 2
Enter movies seen by student 5: 3
Enter movies seen by student 6: 1
Enter movies seen by student 7: 3

Sorted movie counts: 1 1 2 3 3 3 4

Statistical Data:
Average: 2.43
Median: 3.00
Mode: 3

22
LAB
3 LAB 3: STRUCTURES

3.1 Student Structure Declaration and Printing

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

3.2 Book Structure Initialization and Printing

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
23
3.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

3.4 Customer Structure - User Input

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, customer.name);
for strings with spaces.
5. Print the entered customer information to the console.

24
Example Input/Output:

Enter customer name: Robert Mwaza


Enter customer address: P/Bag 303, Chichiri
Enter customer category (A, B, C): B
Enter discount percentage: 5.0
Enter total invoice amount year to date: 5000.25

Customer Information:
Name: Robert Mwaza
Address: P/Bag 303, Chichiri
Category: B
Discount: 5.00%
Total Invoice YTD: MK 5000.25

3.5 Customer Structure Array - User Input

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:").

25
Example Input/Output:

Enter details for Customer 1:


Enter name: Alice Banda
Enter address: P.O Box 202, Zomba
Enter category (A, B, C): A
Enter discount: 12.0
Enter total invoice YTD: 25000.00

Enter details for Customer 2:


Enter name: Bob Kamwera
Enter address: P/Bag 3022
Enter category (A, B, C): C
Enter discount: 2.5
Enter total invoice YTD: 1500.75

Enter details for Customer 3:


Enter name: Carol Gunda
Enter address: P.O Box 2350
Enter category (A, B, C): B
Enter discount: 7.0
Enter total invoice YTD: 8180.50

--- Customer 1 ---


Name: Alice Banda
Address: P.O Box 202, Zomba
Category: A
Discount: 12.00%
Total Invoice YTD: MK25000.00

--- Customer 2 ---


Name: Bob Kamwera
Address: P/Bag 3022
Category: C
Discount: 2.50%
Total Invoice YTD: MK1500.75

--- Customer 3 ---


Name: Carol Gunda
Address: P.O Box 2350
Category: B
Discount: 7.00%
Total Invoice YTD: MK8180.50

26
3.6 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:

--- Employee 1 ---


Name: John Banda
ID: 101
Salary: 55000.00

--- Employee 2 ---


Name: Emily Dzodzi
ID: 102
Salary: 62000.50

--- Employee 3 ---


Name: David Kamwendo
ID: 103
Salary: 48000.75

27
3.7 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:

Initial Car Details:


Make: Toyota
Model: Camry
Year: 2020
Price: 25000000.00

Updating car price...

Updated Car Details:


Make: Toyota
Model: Camry
Year: 2020
Price: 23500000.00

28
3.8 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.,
employee.address.street = "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

3.9 Rectangle Structure: Area Calculation and Dimension


Update by Reference

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 rect.length * rect.width.
3. Define a function updateDimensions that takes a Rectangle object by reference
(Rectangle& rect), a float newLength, and a float newWidth. Inside, set
rect.length = newLength; and rect.width = newWidth;.

29
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...

Updated Rectangle: Length = 12.0, Width = 6.0


New Area: 72.00

3.10 Savings Account Structure with Menu

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).

30
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:

Welcome to Savings Account Manager!


1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit
Enter your choice: 1

Enter Account Number: 12345


Enter Account Balance: 1000.00
Enter Interest Rate (e.g., 0.02 for 2%): 0.015
Enter Average Monthly Balance: 950.00
1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit
Enter your choice: 2

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

Enter deposit amount: 200.00


Deposit successful! New balance: MK1200.00
1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit
Enter your choice: 4

31
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

Enter your choice: 4


Enter withdrawal amount: 1200.00
Insufficient funds! Current balance: MK1050.00
1. Enter Account Data
2. Show Account Data
3. Deposit
4. Withdraw
5. Exit

Enter your choice: 5


Exiting program. Goodbye!

3.11 Company Division Sales Data

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.

32
b. Assign initial names to each division (e.g., east.name = "East";).
c. Call calculateSalesData for each of the four division variables.
d. Call displayDivisionData for each of the four division variables.

Example Input/Output:

Enter sales data for East Division:


Enter Q1 sales: 100000.00
Enter Q2 sales: 120000.00
Enter Q3 sales: 110000.00
Enter Q4 sales: 130000.00

Enter sales data for West Division:


Enter Q1 sales: 95000.00
Enter Q2 sales: 105000.00
Enter Q3 sales: 98000.00
Enter Q4 sales: 112000.00

Enter sales data for North Division:


Enter Q1 sales: 80000.00
Enter Q2 sales: 85000.00
Enter Q3 sales: 82000.00
Enter Q4 sales: 90000.00

Enter sales data for South Division:


Enter Q1 sales: 150000.00
Enter Q2 sales: 145000.00
Enter Q3 sales: 160000.00
Enter Q4 sales: 155000.00

--- Company Sales Report ---


Division: East
Total Annual Sales: MK460000.00
Average Quarterly Sales: MK115000.00

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

33
3.12 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 = actual.category -
budgeted.category.
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.

34
Example Input/Output:

Welcome to Monthly Budget Tracker!

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

Category | Budgeted | Actual | Over/Under


---------------------------------------------------------
Housing | MK5000.00 | MK5100.00 | MK100.00 Over
Utilities | MK1500.00 | MK1400.00 | MK100.00 Under
H/hold expenses | MK650.00 | MK700.00 | MK50.00 Over
Transportation | MK500.00 | MK550.00 | MK50.00 Over
Food | MK2500.00 | MK2400.00 | MK100.00 Under
Medical | MK300.00 | MK300.00 | MK0.00
Insurance | MK1000.00 | MK1000.00 | MK0.00
Entertainment | MK1500.00 | MK1600.00 | MK100.00 Over
Clothing | MK750.00 | MK700.00 | MK50.00 Under
Miscellaneous | MK500.00 | MK450.00 | MK50.00 Under
----------------------------------------------------------
Total Over/Under Budget for the month: MK0.00

35
LAB
4 LAB 4: STRINGS MANIPULATION

4.1 Character to Character Code

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

4.2 Print Character Multiple Times

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:
#######

36
4.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:

Enter a text: Programming is fun!


Length of the text: 19

4.4 Compare Two Words Lexicographically

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:

Enter first word: zebra


Enter second word: apple
zebra is lexicographically greater than apple

37
4.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:

assuming string is "HelloWorld"


The length of the string is: 10

4.6 Access and Modify Third Character in String

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:

Enter a string: example


Modified string: exzmple

38
4.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:

Original string: reverse


Reversed string: esrever

4.8 String Length Function (Without strlen)

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).

39
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

4.9 Count Vowels and Consonants in String

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:

Enter a string: C++ is awesome!


Number of vowels: 5
Number of consonants: 6

40
4.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:

Input: assuming string "Racecar"


Output: "Racecar" is a palindrome.
Input: assuming string "hello"
Output: "hello" is not a palindrome.

41
4.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!

4.12 Count Words in a Sentence

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.

42
Example Output:
Input: This is a sample sentence.
Output: Number of words: 5

4.13 Convert String to Uppercase (Without Built-in)

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

4.14 Function to Count Words in C-String

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.

43
2. In main:
a. Declare a char array (e.g., char input[256];).
b. Prompt and read a sentence using cin.getline.
c. Call countWords(input) and display the result.

Example Input/Output:
Enter a sentence: Four score and seven years ago.
Number of words: 7

4.15 Sort 10 Strings Alphabetically (Using Pointers)

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::cin.getline.
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.

44
Example Input/Output:

Enter string 1: peach


Enter string 2: apple
Enter string 3: orange
Enter string 4: banana
Enter string 5: grape
Enter string 6: fig
Enter string 7: cherry
Enter string 8: date
Enter string 9: mango
Enter string 10: kiwi

Sorted Strings:
apple
banana
cherry
date
fig
grape
kiwi
mango
orange
peach

4.16 Dynamically Allocated 2D String Array with Operations

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.

45
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

46
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 -->

4.17 Capitalize First Character of Each Sentence

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::cin.getline.
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.

47
4.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 password.length() >= 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:

Enter your password: MyP@ss1


Password meets all criteria.

Enter your password: short


Password must be at least 6 characters long.
Password must contain at least one uppercase letter.
Password must contain at least one digit.

Enter your password: NOPASSWORD


Password must contain at least one lowercase letter.
Password must contain at least one digit.

48
LAB
5 LAB 5: CLASSES AND OBJECTS

5.1 Rectangle Class Definition

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

5.2 Circle Class with Constructor and Area Calculation

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;.

49
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:

Circle Radius: 5.00


Circle Area: 78.54

5.3 Student Class with Parameterized Constructor

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

50
5.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)

51
5.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)

52
5.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().

53
Example Input/Output:

Enter details for Employee 1:


Enter Name: Alice Kaliwo
Enter Employee ID: 101
Enter Salary: 65000.00

Enter details for Employee 2:


Enter Name: Bob Kamba
Enter Employee ID: 102
Enter Salary: 72500.50

Enter details for Employee 3:


Enter Name: Charlie Zathu
Enter Employee ID: 103
Enter Salary: 60000.75

--- Employee Details ---


Employee 1:
Name: Alice Kaliwo
ID: 101
Salary: 65000.00

Employee 2:
Name: Bob Kamba
ID: 102
Salary: 72500.50

Employee 3:
Name: Charlie Zathu
ID: 103
Salary: 60000.75

5.7 Date Class with Three-Parameter Default Constructor and


Formats

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.

54
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:

--- Valid Date ---


3/15/25
March 15, 2025
15 March 2025

--- Invalid Date (using defaults) ---


1/1/25
January 1, 2025
1 January 2025

--- Default Date ---


1/1/25
January 1, 2025
1 January 2025

55
5.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.

56
Example Input/Output:

Enter the number of phones ordered: -5


Number of phones ordered cannot be negative. Please enter
again: 1000

To produce 1000 phones, it will take 7 days.

57
LAB
6 LAB 6: INHERITANCE

6.1 Inheritance: Person and Student Classes

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

6.2 Polymorphism: Shape, Rectangle, and Circle

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).

58
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:

Rectangle Area: 50.00


Circle Area: 78.54

6.3 Inheritance with Parameterized Constructor (Base Class


Call)

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;.

59
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

6.4 Protected Members Inheritance

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

60
6.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 b.length * b.width * b.height (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:

Volume of the Box: 100.00


Volume of the ColorBox: 24.00

6.6 Inheritance for Account Types (Interest Calculation)

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.

61
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

Current Account Balance: MK50000.00


Current Interest: MK250.00

6.7 Abstract Base Class with Pure Virtual Function

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,

62
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:

--- Book Details ---


Title: The Great Novel
Author: Jane Phiri
Pages: 300

--- Video Details ---


Title: Epic Movie
Director: John Chidothi
Duration: 120 minutes

6.8 Multiple Inheritance: Person, Worker, and Engineer

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):

63
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:

Enter Person Name: Mark Engineer


Enter Person Age: 30
Enter Worker ID: 5001
Enter Worker Salary: 75000.00

--- Engineer Details ---


Name: Mark Engineer
Age: 30
Work ID: 5001
Salary: 750000.00

6.9 Virtual Inheritance: Person, Employee, Student,


WorkingStudent
Objective:
Create a Person class. Derive Employee and Student from Person. Further derive
WorkingStudent from both Employee and Student using virtual inheritance to ensure
Person's attributes are not duplicated.

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):

64
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:

Working Student Details:


Name: David Banda
Employee ID: 12345
GPA: 3.95

65
LAB
7 LAB 7: POLYMORPHISM AND ENCAPSULATION

7.1 Overload Prefix Increment (++) Operator

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

7.2 Overload Addition (+) Operator for Complex Numbers

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:

66
o Parameterized constructor to initialize real and imag.
o Overload operator+(const Complex& other):
▪ Create a Complex temporary object.
▪ Set temp.real = this->real + other.real;.
▪ Set temp.imag = this->imag + other.imag;.
▪ 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

7.3 Overload Stream Insertion (<<) Operator

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 rect.length and rect.width into os.
c. Return os.
3. In main function:
a. Create a Rectangle object.
b. Print the Rectangle object directly using cout << myRect;.

67
Example Input/Output:

Rectangle: Length = 10.5, Width = 5.2

7.4 Function Overloading Example (Area Calculation)

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:

Area of Rectangle (10x5): 50.00


Area of Circle (radius 3.0): 28.27
Area of Triangle (base 8.0, height 4.0): 16.00

7.5 Overload + and - Operators for Complex Numbers

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;.

68
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

7.6 Virtual Function getRole() with Inheritance

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"; }.

69
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

7.7 Run-Time Polymorphism with draw() Function

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

70
7.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.

71
Example Input/Output:

Car Fuel Efficiency: 12.50 km/liter


Motorcycle Fuel Efficiency: 25.00 km/liter
Truck Fuel Efficiency: 5.00 km/liter

7.9 Calculate Salary (Employee Hierarchy)

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:

Salary for Alice (FullTime): 600000.00


Salary for Bob (PartTime): 15000.00

72
7.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:

Humans breathe with lungs.


Fish breathe with gills.

7.11 Person Class with Getters and Setters

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;.

73
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:

Initial Person Details:


Name:
Age: 0
Grade: 0.00

Setting details...

Updated Person Details:


Name: Emily Gama
Age: 22
Grade: 3.75

7.12 Most Expensive Book Finder (Using Getters)

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;.

74
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

Most Expensive Book:


Title: Book B
Author: Author Y
Price: 350.50

7.13 Company Class with Static Data Member

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;.

75
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:

Initial Total Employees: 0

Creating Company A...


Company A Info: Name = TechCorp, Location = BT City
Adding 10 employees to TechCorp.
Total Employees: 10

Creating Company B...


Company B Info: Name = Innovate Solutions, Location = LL
City
Adding 5 employees to Innovate Solutions.
Total Employees: 15

Removing 2 employees from TechCorp.


Total Employees: 13

7.14 BankAccount Class with Read-Only Balance

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; }.

76
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 myAccount.balance (this should result in a
compile-time error).
c. Successfully read myAccount.getBalance().
d. Demonstrate that attempts to modify balance directly will fail.

Example Input/Output:

Account Number: ABC123


Current Balance: 1000.50

Attempting to directly modify balance...


(This will cause a compile-time error, proving encapsulation)

Example showing attempted direct modification (will fail at


compile time):
// myAccount.balance = 2000.0; // ERROR: 'balance' is private

7.15 Flight Reservation System Class

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.

77
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:

Initial Flight Details:


Flight: BA123
Destination: Lilongwe
Departure: 10:00 AM
Seats Available: 100

Attempting to reserve 5 seats...


Reservation successful! 5 seats reserved.
Current Seats Available: 95

Attempting to reserve 100 seats...


Reservation failed! Not enough seats available.
Current Seats Available: 95

Attempting to reserve 95 seats...


Reservation successful! 95 seats reserved.
Current Seats Available: 0

Final Flight Details:


Flight: BA123
Destination: Lilongwe
Departure: 10:00 AM
Seats Available: 0

78
LAB
8 LAB 8: TEMPLATES

8.1 Template Function findMax()

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

8.2 Template Function swapValues()

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.

79
Example Input/Output:

Initial integers: num1 = 10, num2 = 20


After swap: num1 = 20, num2 = 10

Initial strings: str1 = hello, str2 = world


After swap: str1 = world, str2 = hello

8.3 Templates for min() and max() Functions


Objective:
Write C++ template functions min() and max(), each accepting two arguments and returning
the lesser or greater value respectively. Design a simple driver program to demonstrate these
templates with various data types.

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:

Min of 5 and 10 is: 5


Max of 5 and 10 is: 10

Min of 3.14 and 2.71 is: 2.71


Max of 3.14 and 2.71 is: 3.14

Min of 'c' and 'a' is: a


Max of 'c' and 'a' is: c

Min of "apple" and "banana" is: apple


Max of "apple" and "banana" is: banana

80
8.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)

8.5 Template Function total() for Running Sum

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:

81
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.

Example Input/Output (Interactive Session):

Enter integers to sum (0 to quit):


10
5
15
0
Total integer sum: 30

Enter doubles to sum (0 to quit):


2.5
3.0
4.5
0
Total double sum: 10.0

8.6 Template Function printArray()

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.

82
Example Input/Output:
Integer array: 1 2 3 4 5
Float array: 1.1 2.2 3.3 4.4

8.7 Template Function for Absolute Value

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:

Absolute value of -5 is: 5


Absolute value of 10 is: 10
Absolute value of -3.14 is: 3.14
Absolute value of 7.89 is: 7.89

8.8 Template Function sortArray() using Bubble Sort

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.

83
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:

Original integer array: 5 2 8 1 9


Sorted integer array: 1 2 5 8 9

Original float array: 3.5 1.2 4.8 2.1


Sorted float array: 1.2 2.1 3.5 4.8

8.9 Template Function findMinMax() for Array

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];.

84
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

Float array: 5.5 1.1 8.8 2.2


Min: 1.1, Max: 8.8

8.10 Template Function isEqual() with char Specialization

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).
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.

85
Example Input/Output:

Comparing ints (5, 5): Equal


Comparing ints (5, 10): Not Equal

Comparing floats (3.14, 3.14): Equal


Comparing floats (3.14, 3.15): Not Equal

Comparing chars ('A', 'A'): Equal


Comparing chars ('A', 'a'): Equal (case-insensitive)
Comparing chars ('A', 'B'): Not Equal

8.11 Template Function compareThree()

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:

Largest of 10, 5, 20 is: 20


Largest of 3.1, 8.2, 5.0 is: 8.2
Largest of 100.5, 99.9, 101.1 is: 101.1

86
8.12 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:
result.data[i][j] = this->data[i][j] +
other.data[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.

87
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

88
LAB
9 LAB 9: FILE HANDLING

9.1 Save Classmate Details to File

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 "classmates.txt". The program
should append new information to the file on subsequent runs.

Steps:
1. Open a file named "classmates.txt" 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:

Enter First Name: Alice


Enter Surname: Banda
Enter Age: 20
Enter District: Dowa
Enter Phone Number: 0912345678

Output (to console):


Details saved to classmates.txt

(Content of classmates.txt after multiple runs):


Alice,Banda,20,Dowa, 0912345678
Bob,Phiri,21,Zomba, 0812345678

89
9.2 Read Classmate Information from File

Objective:
Write a C++ program that reads the classmate information from the "classmates.txt" file
(created in the previous program) and prints it on the screen.

Steps:
1. Open the file named "classmates.txt" 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:

Input (from classmates.txt file):


Alice,Banda,20,Dowa, 0912345678
Bob,Phiri,21,Zomba, 0812345678

Output (to console):


--- Classmate Details ---
First Name: Alice
Surname: Banda
Age: 20
District: Dowa
Phone Number: 0912345678
-------------------------
First Name: Bob
Surname: Phiri
Age: 21
District: Zomba
Phone Number: 0812345678
-------------------------

9.3 Count Vowels in a Text File

Objective:
Write a C++ program to count the number of vowels (a, e, i, o, u, case-insensitive) present
in a text file named "class.txt".

90
Steps:
1. Create a "class.txt" file with some sample text.
2. Open "class.txt" in read mode.
3. Initialize a vowelCount variable to 0.
4. Read the file character by character using a while loop and
inFile.get(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:

Input (from class.txt):


Hello World! This is a test file.

Output (to console):


Number of vowels in class.txt: 10

9.4 Count Words in a Text File

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., "words.txt") 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 words.txt):
This is a sample file.
It has some words.

Output (to console):


Number of words in the file: 10

91
9.5 Copy File Content

Objective:
Develop a C++ program that copies the content of a file named "source.txt" to another file
named "destination.txt".

Steps:
1. Create "source.txt" with some sample content.
2. Open "source.txt" in read mode.
3. Open "destination.txt" in write mode (will create/overwrite).
4. Check if both files were opened successfully.
5. Read "source.txt" line by line using getline().
6. Write each line read from "source.txt" to "destination.txt".
7. Close both files.

Example Input/Output:

Input (from source.txt):


Line 1 from source.
Line 2 from source.

Output (to console):


Content copied from source.txt to destination.txt

Output (content of destination.txt):


Line 1 from source.
Line 2 from source.

9.6 File Copy Function (without rdbuf())

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 "input.txt" and open it for reading.

92
4. Open "output.txt" for writing.
5. Call file_copy with the opened file streams.
6. Close both files in main.

Example Input/Output:

Input (from input.txt):


This is line one.
This is line two.

Output (to console):


File copied successfully using file_copy function.

Output (content of output.txt):


This is line one.
This is line two.

9.7 Read/Write Array of Integers to Binary File

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 "data.bin" in binary output mode (ios::out | ios::binary).
b. Use outFile.write(reinterpret_cast<char*>(array_name),
size_in_bytes); to write the entire array.
3. Read from binary file:
a. Open "data.bin" in binary input mode (ios::in | ios::binary).
b. Define a new array (or use a buffer) to store read data.
c. Use inFile.read(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:

Original array written to binary file: 10 20 30 40 50


Array read from binary file: 10 20 30 40 50

93
9.8 Display Lines Starting with 'M' or 'N'

Objective:
Write a C++ program to read the content of a text file "class.txt" and display all lines that start
with either 'M' or 'N' (case-insensitive).

Steps:
1. Create a "class.txt" file with lines, some starting with 'M' or 'N'.
2. Open "class.txt" 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:

Input (from class.txt):


Morning walk
Night sky
Apple pie
Mango juice
Nested loops

Output (to console):


Morning walk
Night sky
Mango juice
Nested loops

9.9 Count Lines in a Text File

Objective:
Write a C++ program that reads a text file named "data.txt" line by line and counts the total
number of lines in the file, then prints the total count.

Steps:
1. Create a "data.txt" file with some multi-line content.
2. Open "data.txt" in read mode.
3. Initialize lineCount to 0.
4. Read the file line by line using getline() in a while loop.

94
5. Increment lineCount for each line read.
6. Print the lineCount.
7. Close the file.

Example Input/Output:

Input (from data.txt):


This is line 1.
This is line 2.
This is line 3.

Output (to console):


Total number of lines in data.txt: 3

9.10 Copy Integers from Binary File to another Binary File

Objective:
Write a C++ program that reads an array of integers from a binary file named "data.bin" and
writes them to a new binary file named "copy.bin".

Steps:
1. First, ensure "data.bin" exists and has some integer data (e.g., from problem 9.7).
2. Open "data.bin" for reading in binary mode (ios::in | ios::binary).
3. Open "copy.bin" for writing in binary mode (ios::out | ios::binary).
4. Check if both files were opened successfully.
5. Determine the size of "data.bin" (to know how many integers to read).
6. Read integers from "data.bin" in chunks or one by one. For simplicity, read into a
buffer.
7. Write the read integers from the buffer to "copy.bin".
8. Close both files.

Example Input/Output:

Input (from data.bin, e.g., 5 integers): (binary data)

Output (to console):


Integers copied from data.bin to copy.bin

95
9.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
"students.txt", calculates, and displays the average score of all students.

Steps:
1. Create a "students.txt" file with sample student names and scores (e.g., "Alice
85", "Bob 90").
2. Open "students.txt" 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:

Input (from students.txt):


Alice 85.0
Bob 90.0
Charlie 75.0

Output (to console):


Average score of students: 83.33

96
9.12 Sum and Average from File to File

Objective:
Write a C++ program that reads a list of numbers from a file named "numbers.txt", calculates
their sum and average, and writes these results to another file named "results.txt".

Steps:
1. Create "numbers.txt" with one number per line or space-separated numbers.
2. Open "numbers.txt" for reading.
3. Open "results.txt" for writing.
4. Check if both files opened successfully.
5. Initialize sum = 0.0 and count = 0.
6. Read numbers from "numbers.txt" 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 "results.txt".
10. Close both files.

Example Input/Output:

Input (from numbers.txt):


10.5
20
5.5
30

Output (to console):


Sum and average calculated and written to results.txt

Output (content of results.txt):


Sum: 66.00
Average: 16.50

97
9.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: sample.txt
Enter word to search: the

Output (from sample.txt):


This is the sample text.
The word 'the' appears multiple times.

Output (to console):


The word 'the' appears 2 times in sample.txt

9.14 Write and Read Student Records to/from File

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.

98
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

Output (to console):


Student records written to students_records.txt
--- Student Records from File ---
Name: Chris, ID: 111
Name: Dana, ID: 222

9.15 Sort Lines in a File and Write to New File

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.

99
2. Read Lines:
a. Open "unsorted.txt" 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 "sorted.txt" for writing.
b. Loop through the sorted lines array and write each char* (line) to
"sorted.txt".
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:

Input (from unsorted.txt):


zebra
apple
orange
banana

Output File: sorted.txt


apple
banana
orange
zebra

9.16 Check File Existence, Readability, and Writability

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).

100
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.

Example Input/Output (for an existing, accessible file):

Input:
Enter filename: existing_file.txt

Output:
File 'existing_file.txt' exists.
File 'existing_file.txt' is readable.
File 'existing_file.txt' is writable.

Example Input/Output (for a non-existent file):

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)

101
9.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.

Example Input/Output (for a non-existent file):

Input:
Enter filename: non_existent_file.txt

Output:
Error: Could not open non_existent_file.txt for reading.
Exiting program

Example Input/Output (for an existent file):

Input:
Enter filename: existent_file.txt

Output:
Successfully opened existent_file.txt for reading.

102
9.18 Read CSV File and Print Rows

Objective:
Write a C++ program that reads a CSV file named "data.csv" line by line, splits each line into
fields based on the comma delimiter, and prints each field to the console.

Steps:
1. Create a "data.csv" file with comma-separated values (e.g.,
Name,Age,City\nAlice,25,NY).
2. Open "data.csv" 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:

Input (from data.csv):


Header1,Header2,Header3
Value1,Value2,Value3
Another1,Another2,Another3

Output (to console):


Row 1: Header1 Header2 Header3
Row 2: Value1 Value2 Value3
Row 3: Another1 Another2 Another3

103
9.19 Replace Word in Text File and Save to New File

Objective:
Write a C++ program that reads a text file named "document.txt", 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 "document.txt" file with some content.
2. Prompt the user for the word to find and the word to replace it with.
3. Open "document.txt" for reading.
4. Check if the file opened successfully.
5. Read the entire content of "document.txt" 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:

Input (from document.txt):


This is a test document.
Test word occurrences.

Input (from user):


Enter word to find: test
Enter word to replace with: sample

Output (to console):


Word replacement complete. Modified text saved to
modified_document.txt

Output (content of modified_document.txt):


This is a sample document.
Sample word occurrences.

104

You might also like