[go: up one dir, main page]

0% found this document useful (0 votes)
14 views60 pages

181 Lab v2.1

The document is a laboratory booklet for the Computer Programming II (C++) course at Qassim University, detailing lab activities, objectives, and programming tasks. It includes a revision history, a table of contents, and various programming exercises designed to teach C++ concepts such as arithmetic operations, selection statements, and functions. Students are encouraged to practice coding and problem-solving skills through hands-on activities and projects.

Uploaded by

khzybwfwv2
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)
14 views60 pages

181 Lab v2.1

The document is a laboratory booklet for the Computer Programming II (C++) course at Qassim University, detailing lab activities, objectives, and programming tasks. It includes a revision history, a table of contents, and various programming exercises designed to teach C++ concepts such as arithmetic operations, selection statements, and functions. Students are encouraged to practice coding and problem-solving skills through hands-on activities and projects.

Uploaded by

khzybwfwv2
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/ 60

Qassim University

College of Computer
Computer Science Department

Laboratory Booklet

for

Computer Programming II (C++)


(CS181)
Revision History
Name Contribution Date Version
Mr. Faisal Alhwikem First author 30 Nov 2012 1.0
Mr. Faisal Alhwikem Update content 01 May 2014 2.0
Mr. Mohamad Algasham Convert from (odt) to (docx) 01 Sep 2021 3.0
Dr. Faisal Alhwikem Minor content update 25 Nov 2021 3.1
Mr. Osama Alzakan Change to C++ 25 Aug 2024 4
Table of Contents
4 .......................... ................................ ................................ Lab 01: Introduction
6 ...................................... ................................ Lab 02: Basic arithmetic operations
8 .............. ................................ Lab 03: Selection statements and repetitive statements
13 ............ ................................ ................................ Lab 04: Repetitive statements
17 .................. ................................ ................................ Lab 05: Functions (part 1)
20 .................. ................................ ................................ Lab 06: Functions (part 2)
26 ...................... ................................ ................................ Lab 07: Arrays (part 1)
30 ...................... ................................ ................................ Lab 08: Arrays (part 2)
34 ............................... ................................ ................................ Lab 09: Pointers
42 ........ ................................ ................................ Lab 10: String handling functions
46 ................... ................................ ................................ Lab 11: Structure (part 1)
50 ................... ................................ ................................ Lab 12: Structure (part 2)
54 .................... ................................ ................................ Lab 13: Structure (part 3)
58 ................... ................................ ................................ Lab 14: Files Processing
60 ................... ................................ Lab 15: Bitwise Operators, Enumeration and Union
Lab 01: Introduction

Objectives
• Introduce the lab content and structure.
• To be able to create a C++ source file and add code to it.
• To understand how to declare variables and assign values to them.
• To do simple arithmetic operations against variables and their values.
• To understand the precedence of arithmetic operations.

This module (CS181) introduces computer programming and problem-solving using the C++
programming language. Computer labs will help you understand the concepts covered in
lectures and will help in your assignments and examinations. Therefore, it is highly
recommended that you do all the exercises and tasks of lab activities in this booklet.
Nevertheless, the materials you are taking in lectures and practical sessions may not completely
cover the C++ programming language.

Student Responsibility
• Attend Lectures, Labs. Be motivated.
• Prepare before you come to classes and labs.
• The key to learning a programming language is to practice it whenever possible.
• Remember! lectures and labs are insufficient to cover the C++ programming
language.
• Time management will help you to be successful.
• WORK HARD! Do not underestimate the load of this course. Start as early as
possible to practice the C++ language and do problem-solving.

Requirements
You need to be able to write C++ code. The choice of software is left to you, but we
recommend that basic text editors and terminals (e.g., GCC) to execute your code. You also
may use online C compilers if you please. All we need is to be able to inspect the code, run
it, and get actual outputs. The following is a list of recommended applications.
1. Visual Studio Code (highly recommended): [https://code.visualstudio.com]
2. Visual Studio C++: [https://visualstudio.microsoft.com/vs/features/cplusplus/]
3. Eclipse IDE with C/C++ compatibility:
[https://www.eclipse.org/downloads/packages/release/kepler/sr2/eclipse-ide-cc-
developers]
For installation, you can find plenty of resources and tutorials online that align with your
specific desires, preferences, and operating systems.

Activity 1
Write a C++ program that prints into the standard output the famous statement “Hello
World.” You can try the following:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}

#include <iostream>
using namespace std;
int main() {
cout << "Hello, world!" << endl;
return 0;
}
Lab 02: Basic arithmetic operations

Objectives
• To be able to create a C++ source file and add code to it.
• To understand how to declare variables and assign values to them.
• To do simple arithmetic operations against variables and their values.
• To understand the precedence of arithmetic operations.

Practise

cout << "Value = " << 4 + 3 << std::endl; // output Value = 7

#include <iostream>
using namespace std;
int main() {
int age, nID, sID;
cout << "Enter your age: ";
cin >> age;
cout << "Enter your national ID: ";
cin >> nID;
cout << "Enter your social ID: ";
cin >> sID; // Use the entered values here
return 0;
}

Task :
Print the information user entered.

Practise 2
Indicate which lines of the following program have errors.
#include <iostream>
using namespace std;
int main ()
{
cout >> "Program to find area of a trapezium: ";
int a,b,h;
float area;
cout << "Enter values of a and b, and h:";
cin >> a >> b >> h;
area = (h/2)*(a+b);
cout << "The area is "area;
return a;
}

Activity 1:
#include <iostream>
using namespace std;
int main() {
int var1, var2, result;
cout << "Enter first number: ";
cin >> var1;
cout << "Enter second number: ";
cin >> var2; result = var1 + var2;
cout << "Result = " << result << endl;
return 0;
}

Task 1.1: Add a new integer variable ‘var3’ and add necessary statements to allow the
program to sum all three variables, which are all integer types.
Task 1.2: Change the previous program to perform the following formula
𝒓𝒆𝒔𝒖𝒍𝒕 = (var1 + var2) ∗ var3
Task 1.3: change the types of all variables and make them double.

Activity 2
Write a C++ program that finds the volume of a frustum of a cone (as depicted in the figure).

𝟏
𝑽 = 𝟑 𝝅 𝒉 (𝒓𝟐𝟏 + 𝒓𝟏 𝒓𝟐 + 𝒓𝟐𝟐 ), where π = 3.14

The unknowns, which are h, r1, and r2, must be entered by the user.
Hint: consider using double datatype for the unknowns. Also, do not forget to have the
𝟏
fraction 𝟑 as (0.333) or 1.0/3.0 or have it as

((int) 1 / (int) 3).


Lab 03: Selection statements and repetitive statements

Lab Objectives
• To understand basic problem-solving techniques.
• To be able to develop algorithms through the process of top-down, stepwise
refinement.
• To be able to use the selection statements of C++ language
• Understand switch statement
• Understand looping/repetitive statements (while, for, do…while)
• Understand increment and decrement Operators
• Finding unacceptable behaviours using simple test cases
• Understand software corrections.

switch statement
The switch statement is used when there are multiple values of a single variable are expected.

Practise
What is printed after executing the following program?
#include <iostream>
using namespace std;
int main(){
int a = 1, b = 0, c = 1, val1, val2, val3, val4;

val1 = a || b || c;
val2 = a && b && c;
val3 = a || b && c;
val4 = a && b || c;

cout<< val1 << val2 << val3 << val4;

return 0;
}

Activity 1
Create a new Console Application and add a new C++ file with the code below. This
program reads a mark from the user and prints the corresponding grade.
#include <iostream>
int main() {
int mark;
std::cout << "Enter the mark" << std::endl;
std::cin >> mark;
if (mark >= 90) {
std::cout << "A" << std::endl; }
else if (mark >= 80) {
std::cout << "B" << std::endl; }
else if (mark < 60) {
std::cout << "F" << std::endl; }
return 0;
}

Task 1.1: There are two grade specifications missed in the last program: C grade and D
grade. Modify the code in Task 1.1 to allow these two grades to be counted.
C: 80 > mark ≥ 70
D: 70 > mark ≥ 60

Activity 2
Create a new Console Application and add a C++ file with the code below. This code finds
the maximum number of three integers entered by the user.
#include <iostream>
int main() {
int a, b, c;
std::cout << "Enter 3 numbers: ";
std::cin >> a >> b >> c;

// Finding the maximum


int max = a; // Assume 'a' is the largest initially

if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
std::cout << "Max = " << max << std::endl;
return 0;
}

Task 2.1: Modify the previous code in Task 2.1, so it would be able to find the minimum
number of three numbers beside the maximum number.
Activity 3
Create a new project and add a new C++ file with the code below. This code asks the user to
select one of the operations (+, -, /, ×) and enter two numbers to perform the calculation.
#include <iostream>

int main() {
char input;
std::cout << "Enter an operation (+, -, x, /, %): ";
std::cin >> input;

int a, b;
std::cout << "Enter two numbers for calculation: ";
std::cin >> a >> b;

switch (input) {
case '+':
std::cout << "Adding = " << (a + b) << std::endl;
break;
case '-':
std::cout << "Subtracting = " << (a - b) << std::endl;
break;
default:
std::cout << "The operation is not valid." << std::endl;
}

return 0;
}

Task 3.1: The previous code is missing the implementation of three more operations:
multiplication, division, and modulo operations (x, /, %). Do the necessary to add these
operations in the code.
In the case of a division operation, make sure that you do not allow the division on zero. In
the case of modulo operation, make sure that you have the bigger number over the small
number.

Activity 4
Create a new project and add a new C++ file with the code below. This program computes
the average of 10 grades entered by the user.
#include <iostream>
#include <iomanip> // For std::setprecision

using namespace std;

int main() {
double total = 0.0, grade = 0.0;
int counter = 1;

while (counter <= 10) {


cout << "Enter grade: ";
cin >> grade;
total += grade;
counter++;
}

double average = total / 10.0;


cout << "Class average is " << fixed << setprecision(2) << average <<
endl;

return 0;
}

Task 4.1: The previous code always computes the average of exactly 10 grades entered by
the user. How may you change the code to make it flexible and add ‘numberOfGrades’
variable that allows the user to enter beforehand the number of grades that he/she wants for
computation.
Task 4.2: Replace the while loop with a for loop and make necessary changes.

Activity 5
Create a new project and add a C++ file with the following code. This program asks the user
to enter as many grades as he/she desires and then computes the total and the average of all
𝒕𝒐𝒕𝒂𝒍 𝒔𝒖𝒎
entered grades ( 𝒂𝒗𝒈 = ). The user can always enter -1 at any time to terminate the
𝒄𝒐𝒖𝒏𝒕
loop of entering grades.
#include <iostream>
#include <iomanip> // For std::setprecision

using namespace std;

int main() {
double total = 0.0;
int counter = 0;
double grade = 0.0;

cout << "Enter grade (-1 to end): ";


cin >> grade;

while (grade != -1) {


total += grade;
counter++;

cout << "Enter grade (-1 to end): ";


cin >> grade;
}
double average = total / counter; cout << "Class average = " <<
fixed << setprecision(4) << average << endl;

return 0;
}

Task 5.1: Test the previous program with the following inputs. Describe any behaviours.
Test 1 Test 2 Test 3
10 9 -1
9 -1
8
-1

Task 5.2: How might you improve the code to overcome any unacceptable behaviors in the
program in Task 5.1?
Task 5.3: The user wants also to find the minimum and the maximum of all entered grades.
How might you modify the code to allow this new requirement?
Hint: assume the biggest number for the minimum variable and the smallest number for the
maximum variable with which you start.

Activity 6
Write a C++ program that asks for a distance in miles and converts it to Kilometers. (One
mile is 1.6 Kilometer)
Lab 04: Repetitive statements

Objectives
• To be able to solve problems
• To be able to implement simple algorithms to solve simple problems
• To be able to user continue and break with loops

Activity 1
Write a C++ program that prints numbers from 1 to a maximum number entered by the user.

Activity 2
Write a C++ program that keeps printing numbers starting from 1 to 10. You must use while
but do not specify any condition for the while. You must use if statement and break
keywords instead. To use while without condition, simply provide while with 1 as indicates
true. (i.e., while (1))

Activity 3
Write a C++ program that keeps printing numbers from 1 to 100 except numbers that are
divisible by 5. You must use for statement but do not specify a condition for it. You must
use if statement and continue, and break keywords.

Activity 4
Write a C++ program to find the average of all odd numbers from 1 to a maximum number
entered by the user.

Activity 5
Write a C++ program that prints the identity matrix of 5 (N = 5).
Hint: Use nested loops (a repetitive statement inside another repetitive statement).
10000
01000
00100
00010
00001
Activity 6
Write a program that prints the following pattern up to 5 columns.
Hint: Use nested loops.
1
22
333
4444
55555
666666

Activity 7
Write a program that prints the following pattern up to 5 columns.
+
+
++*++
+
+

Challenge Activity (optional)


Write a program that prints the following pyramid shape (hint: find the number of columns
required to print).
1
000
11111
0000000
111111111
00000000000
1111111111111

Activity 8
Write a C++ program that will ask the user to input unlimited positive numbers. The program
will terminate if the user input a negative number.

Activity 9
Write a C++ program to input any two numbers x and y from the user and find xy.
For example,
if the user inputs 5 and 3, your code will calculate 53 which is equal to 125
if the user inputs 2 and 8, your code will calculate 28 which is equal to 256
if the user inputs 7 and 5, your code calculate 75 which is equal to 16807.

Activity 10
Write a C++ program to enter a day number (1-7) and print the day name using switch (also
use an infinite loop that terminates by inputting -1 with a farewell message).
Consider:
1 is Sunday
2 is Monday
3 is Tuesday
4 is Wednesday
5 is Thursday
6 is Friday
7 is Saturday
Example Output:
Please enter a day number between (1-7) or (-1 to exit): 2
The day is: Monday
Please enter a day number between (1-7) or (-1 to exit): 5
The day is: Thursday
Please enter a day number between (1-7) or (-1 to exit): -1
Thank you for using the program!

Activity 11
Write a C++ program to print the following pattern:
Hint: Use nested loops.
*******
******
*****
****
***
**
*
Activity 12
Write a C++ program that will ask the user to input a maximum number. The program will
print from maximum number until 1.
Lab 05: Functions (part 1)

Objectives
• To be able to use C++ built-in functions (see https://devdocs.io/cpp/ for more details
about available libraries and header files of C++)
• To understand the mechanisms used to pass information between functions.

Activity 1
Consider the figure shown; we can compute c by using the
Pythagorean Theorem as given by the formula

𝑐 = √(𝑎2 + 𝑏 2 )
Write a C++ program that finds the value of c where the user enters a and b.
You can include the cmath file that contains the functions that you need. You need to use the
following functions
double sqrt(double value): returns the square root of the parameter value
double pow(double base,double exp): returns the power of base to the given
exp

Test:
Inputs Output
a= 2, b= 4 4.47
a= 5, b= 10 11.18

Activity 2

The area of the triangle shown in the figure with sides a,


b, and c can be found by knowing three inputs: two sides
and one angle.
Write a C++ program that asks the user to enter three
unknowns: two sides and one angle (e.g., a, b and angle
C) and then compute the area of the triangle by using the
formula below.
1
𝐴= 𝑎 𝑏 sin(𝐶)
2
Use sin(angle) function that exists in cmath header file to compute the sin angle after
converting it to radian.
Test:
Inputs Output
a= 4, b= 8, C=45 11.31
a= 5, b= 7, C=30 8.75

Activity 3
Write a program that accepts a character from the user and a repeat number of times that
he/she wants that character to be printed on the screen. If the character is an alphabetic one,
then print them horizontally. Otherwise, print the character vertically. If the character is
neither, then don’t print anything.
To be able to check the characters, you can include the cctype header file and then use the
following functions:
int isalpha(int ch): returns 0 if the character is not alphabetic

Test:
Inputs Output
ch=’c’, repeat= 4 cccc

ch=’7’, repeat= 3 7
7
7

Generation of Random Number


We can generate a random integer number by using the rand() function. This function
prototype is in C Standard Library (cstdlib). The number generated is in the range of 0 and
RAND_MAX (32767). If the symbol % is used with the rand(), then the function shall produce
an integer in the range of 0 and whatever number is associated with the symbol %. This action
is known as scaling.
For example, to generate numbers between 0 and 6, then the following should be used.
number = rand() % 7

In general, to generate a random number between the range of min and max integers, then the
below statement is used.
number = min + rand( ) % (max – min + 1)

For example, if we like to generate number between 10 and 20, then the below statement
should be used.
number = 10 + rand( ) % (20 – 10 + 1)

To obtain a different random number in each execution of rand(), we can seed the function
rand() with the current time of the execution by passing time(NULL) to the function
srand() as follows

srand(time(NULL))

time() is a function that returns the current calendar (day and time), and its prototype is in
ctime.

Activity 4
A user wants to find the sum of 30 even random generated numbers of a particular range.
Complete the program below that asks the user to enter the minimum and maximum of the
range that he/she wants. Then, the program must find the sum of all even numbers.
#include <iostream> // For std::cout
#include <cstdlib> // For std::rand and std::srand
#include <ctime> // For std::time

const int numbers = 30; // Use const instead of #define

int main() {
int min, max, sum = 0;

std::srand(static_cast<unsigned int>(std::time(nullptr))); // Seed the


random number generator with the current time

for (int i = 1; i <= numbers; ++i) {

sum +=
}

std::cout << "Sum = " << sum << std::endl; // Print the sum

return 0;
}

Test:
Inputs Output
min=5, max= 100 %depends on your machine%
min=10, max=1000 %depends on your machine%
Lab 06: Functions (part 2)

Objectives
• To understand how to construct programs modularly from small pieces called
functions.
• To understand the mechanisms used to pass information between functions.

Activity 1
The following code asks the user to enter 3 variables: a, b, and c, and then finds the minimum
and the maximum of all three.
#include <iostream> // For std::cout
int main() {
int a, b, c;

// Input from user


std::cout << "Enter 3 Numbers: ";
std::cin >> a >> b >> c;

// Output the results


std::cout << "Min = " << min(a, b, c) << std::endl;
std::cout << "Max = " << max(a, b, c) << std::endl;

return 0;
}
Task 1.1: define the function:
int min(int a, int b, int c)
That turns the minimum value of three given values.
Task 1.2: define the function:
int max(int a, int b, int c)
The function returns the maximum value of three given values.

Activity 2
The following code asks the user to enter number and the exponent in which it will be raised
to. Then the code will find the power and prints it.
#include <iostream> // For std::cout and std::cin
using namespace std; // Use the standard namespace

// Function prototype
double findPower(double base, double exp);

int main() {
double base, exp;

cout << "\nFinding Power...\nEnter Base: ";


cin >> base;
cout << "\nEnter Exponent: ";
cin >> exp;

// Output the result using findPower function


cout << "Result = " << fixed << setprecision(4) << findPower(base, exp)
<< endl;

return 0;
}

Task 2.1: Define the function 'findPower' that receives a base number and an exponent in
which the base must be raised to. The function then returns the power of base. Do not use
the math header file.

Activity 3
The Unit Upper Triangular matrix is a square matrix (same number of rows and columns)
with the following form.

The code below prints on the screen the unit upper triangular matrix of n by calling
'printUnitUpperTriangular'. The size of the matrix is given by the user.
#include <iostream> // For std::cout and std::cin

using namespace std; // Use the standard namespace

// Function prototype
void printUnitUpperTriangular(int n);

int main() {
int n;
cout << "Enter the size of matrix: ";
cin >> n;
printUnitUpperTriangular(n);
return 0;
}
Task 3.1: Write a function 'printUnitUpperTriangular' that receives the size of the matrix and
prints on the screen the Unit Upper Triangular of matrix n. Values of a12, a13, a14, and so on
are all random numbers between 0 and the size of matrix (n) (i.e., rand()%(n + 1)).

Activity 4
Write a recursion function that sums all even numbers from 1 to n, where n is a number
entered by the user.

Activity 5
Indicate which lines of the following program have errors.
#include<iostream>
using namespace std;

void main() {

int first_number;
cout << "Enter First Number : ";
cin >> first_number;

int second_number;
cout << "Enter Second Number: ";
cin << second_number;

int gcd;
for(int i = 1 , i <= first_number && i <= second_number , i++ ){

if(first_number%i == 0 && second_number%i == 0){


gcd = i
}
}

cout << "Greatest Common Divison (GCD) = " << gcd << endl;
return 0;
}

Activity 6
What will be the output for each of the following programs?
#include<iostream>
using namespace std;

void fun(int n, char fp, char tp, char ap){


if(n==1){
cout << fp << tp;
return;

}
fun(n-1,fp,ap, tp);
cout << fp << tp;
fun(n-1,ap,tp,fp);
}

int main(){
fun(2,'x','y','z');
return 0;
}

Activity 7
What will be the output for each of the following programs?
#include<iostream>
using namespace std;

void change(int x, int y, int &z) {


x = y + z;
y = x + z;
z = x + y;
}

int main() {
int i = 2, j = 3;
change(i, j, j);
cout << i << j << endl;
return 0;
}

Activity 6
Write a C++ Program to swap two numbers.

Activity 7
Task 1: Write and understand the following four programs.

Program #1 (C++ inline functions)

#include <iostream>
using namespace std;
inline int add(int a, int b) {
return a + b;
}
int main() {
cout<<add(3, 5);
return 0;
}

Program #2 (Default Arguments)

#include <iostream>
using namespace std;

// function prototype that specifies default arguments


int boxVolume( int length = 1, int width = 1, int height = 1 );

int main(){
cout << "The default box volume is: " << boxVolume();
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume(10);
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume(10, 5);
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 2 is: " << boxVolume(10, 5, 2) << endl;
}
int boxVolume( int length, int width, int height ){
return length * width * height;
}

Program #3 (Function Overloading)

#include <iostream>
using namespace std;
void print(int i) { cout << "Printing int: " << i << endl; }
void print(double f) { cout << "Printing float: " << f << endl; }
void print(char c) { cout << "Printing character: " << c << endl; }
int main(void) {
// Call print to print integer
print(5);
// Call print to print float
print(500.263);
// Call print to print character
print('C');
return 0;
}

Activity 7
Write a C++ program for basic arithmetic operations (add, sub, multiply, div, mod), where
each operation is a function.
Activity 8
Write a function with no parameters to print hello world.
Lab 07: Arrays (part 1)

Objectives
• Continue learning about functions.
• To understand the mechanisms used to pass information between functions.
• To introduce the array data structure.
• To understand the use of arrays to store, sort, and search lists of values.
• To understand how to define an array, initialize an array and refer to individual elements
of an array.
• To be able to pass arrays to functions.

Activity 1
This program gives the users a sort of choices:
1. Test a given number whether it’s even or odd
2. Exit the program
#include <iostream> // For std::cout and std::cin
using namespace std; // Use the standard namespace

// Define a new type called bool using the C++ bool type
typedef bool boolean;

// Prototype: isEven function


boolean isEven(int num);

int main() {
int choice;
boolean exit = false;
int number;

while (!exit) {
cout << "Please select one of the following\n";
cout << "1- Even/Odd integer test? \n";
cout << "2- Exit...\n";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter a number for the test: ";
cin >> number;
if (isEven(number)) {
cout << number << " is even.\n";
} else {
cout << number << " is odd.\n";
}
break;

case 2:
exit = true;
break;

default:
cout << "Invalid entry.\n";
} // end switch
} // end while

return 0;
}

Task 1.2: define the function:


bool isEven(int num)
The function returns true if the given number is even or false otherwise.

Activity 2
This code generates an array of random numbers between MIN and MAX and then computes
the sum of all even numbers in that array.

#include <iostream> // For std::cout and std::cin


#include <cstdlib> // For std::rand and std::srand
#include <ctime> // For std::time

const int MIN = 0;


const int MAX = 10;
const int SIZE = 100;

// Function prototypes
int sumAllEven(const int rand_array[], int array_size);

void generateArray(int randArray[], int size, int randMin, int randMax) {


std::srand(static_cast<unsigned int>(std::time(nullptr))); // Seed the
random number generator
for (int i = 0; i < size; ++i) {
randArray[i] = randMin + std::rand() % (randMax - randMin + 1);
}
}

int main() {
int myArray[SIZE];
generateArray(myArray, SIZE, MIN, MAX);
std::cout << "The sum is " << sumAllEven(myArray, SIZE) << std::endl;
return 0;
}

Task 2.1: define the function


int sumAllEven(const int rand_array[], int array_size);
that returns the sum of all even numbers that exist in the given array. This function receives an
array of random numbers and the size of that array.

You must use the isEven function that you made in Activity 1. Note that the function only
tests one number. You may want to call it several times for all elements of the array.

Activity 3
This code asks the user about a symbol that he would like to search in an array of symbols and
returns the number of appearances of that symbol.

#include <iostream> // For std::cout and std::cin


using namespace std; // Use the standard namespace

// Function prototype
int howManySymbols(const char symbols[], int arraySize, char target);

int main() {
// Declare an array of chars to hold symbols
const int SIZE = 10; // Size defined as a constant
char symbols[SIZE] = {'<', '-', '>', '>', '0', '7', 'a', '>', 'c', '<'};

char target;
int count;

cout << "Which symbol would you like to count: ";


cin >> target;

// Call the function howManySymbols to count the target symbol appearance


in the array symbols
count = howManySymbols(symbols, SIZE, target);

cout << "There are " << count << " of the symbol " << target << " exist."
<< endl;

return 0;
}

Task 3.1: write/define the function:


int howManySymbols(const char symbols[], int arraySize, char target)
The function counts the appearance of the symbol target in the array of symbols. Note that, the
length of the array of symbols is given by arraySize.

Activity 4
Write a program that prints on the screen a summary of character types. That is, a program that
prints how many alphabetic characters, how many numeric characters, and how many symbols
exist in a given character array. You can use the symbols array that is defined in Activity 3.
You need to use the cctype header file and the following functions
int isdigit(int) // returns 0 if the given argument is not digit character
int isalpha(int) // returns 0 if the given argument is not alphabetic
character

Activity 5
Write a C++ program that finds the largest or maximum number in array using for loop and if
statement. Let the user inputs the elements of the array.

Activity 6
Modify the previous code from Task 5 so that it finds the second largest element in an array
using for loop and if statement. Let the user inputs the elements of the array.

Activity 7
Write a C++ program that reads n number of values in an array and display it in reverse
order. Let the user inputs the elements of the array.

Activity 8
Write a C++ program to print all unique elements in an array (i.e. A unique element appears
only once in the array). Let the user inputs the elements of the array.

Activity 9
Write a C++ program to count the frequency of each element of an array.
Lab 08: Arrays (part 2)

Objectives
• To introduce the array data structure.
• To understand the use of arrays to store, sort, and search lists of values.
• To understand how to define an array, initialize an array and refer to individual elements
of an array.
• To be able to pass arrays to functions.
• To be able to work with multi-dimensional arrays

Activity 1
This code prints on the screen the number of available spaces for parking in each list of signs.
The signs are:
• N indicates no parking allowed
• O indicates an occupied park
• B indicates bus stop
◦ There must be two vacant spaces for a bus: one before and one after the bus
stop

#include <iostream> // For std::cout and std::cin


#include <cstdlib> // For std::rand and std::srand
#include <ctime> // For std::time
#include <cstring> // For std::strlen

constexpr int MAXSIZE = 10; // Define MAXSIZE as a constant

// Function prototypes
int countParks(const char street[], int size);
void fillStreet(char street[], int size);

void fillStreet(char street[], int size) {


std::srand(static_cast<unsigned int>(std::time(nullptr))); // Seed the
random number generator
for (int i = 0; i < size; ) {
// Generate random values between 45 and 79
int c = 45 + std::rand() % (79 - 45 + 1);
// Check if c is one of the desired values
if (c == 45 || c == 66 || c == 78 || c == 79) {
street[i++] = static_cast<char>(c); // Store the character
}
}
street[size - 1] = '\0'; // Null-terminate the string
}

int main() {
char street[MAXSIZE];
fillStreet(street, MAXSIZE);
std::cout << "Street = " << street << std::endl;
std::cout << "Number of parks in street = " << countParks(street,
MAXSIZE) << std::endl;
return 0;
}

Task 1.1: Define/Write the function


int countParks(char street [], int size)
that counts available spaces for parking in each list. This function receives an array of chars
and the size of the array.

Test cases
1) OONONON-O : 1 parking space available only
2) O-N-NO-B- : 2 parking spaces. Note that, the empty spaces before and after the bus
stop have not been counted as per the rules.
3) NO-----O- : 6 parking spaces
4) NN-NN-NN- : 3 parking spaces
5) - : 1 parking space
6) NOOOOOOON : 0 parking space
7) -B-OOO-B- : 0 parking space
8) B-O-O-B : 1 parking space
9) --------- : 9 parking spaces

Task1.2: define/write the function


void summary(char street [], int size)
that prints on screen a summary of the street: 1) the number of parked cars, 2) the number of
bus stops, and 3) the number of non-parking allowed spaces (along with the ones that for the
buses).

Activity 2
A fence is defined if it has '-' and/or '|' characters only put next to each other. For example, '|-|-
|-' and '|-|-|' are considered valid fences.

You are given a fence, define/write the function 'longestFence' that finds and returns the longest
fence in a string that is generated randomly with ‘-’ and ‘|’ characters.

Examples:
1. |-|-|- → 6
2. -|--|||-|---|- → 4
3. -|- → 3
4. - → 1
5. | → 1
6. ----- → 1
7. |||||||| → 1
#include <iostream> // For std::cout
#include <cstdlib> // For std::rand and std::srand
#include <ctime> // For std::time

constexpr int MAX = 10; // Define MAX as a constant

// Function prototype
int longestFence(const char input[], int size);

int main() {
char string[MAX];
char c;

std::srand(static_cast<unsigned int>(std::time(nullptr))); // Seed the


random number generator

// Fill the array with random characters


for (int i = 0; i < MAX; ) {
c = 45 + std::rand() % (124 - 45 + 1); // Obtain random characters
if (c == 45 || c == 124) { // Check if c is '-' or '|'
string[i++] = c;
}
}
string[MAX - 1] = '\0'; // Null-terminate the string

// Output the generated string and the longest fence length


std::cout << "String is: " << string << std::endl;
std::cout << "Longest fence = " << longestFence(string, MAX) <<
std::endl;

return 0;
}

Activity 3
Write a C++ program that accepts an array of integers then prints the elements in numerical
order from lowest to highest values (ascending order). Allow the user to input the size of the
array.
Hint: Do not use built-in functions, but use loops to perform the sort. You may want to use
any known sorting algorithms such as bubble sort, insertion sort, selection sort, merge sort,
quick sort, heap sort, etc.

Activity 4
Write a function to calculate the standard deviation of a sequence of integers. Assume that the
first integer read with (cin) specifies the number of values to be entered. Your program should
read only one value each time (cin) is executed. Make use of math built-in functions.
Hint: The standard deviation σ (sigma) can be calculate using the following formula,

where n is the number of integers,


x is the value of each integer in this range,
μ
is the mean value of each integers.
Lab 09: Pointers

Objectives
• To be able to use pointers.
• To be able to generate random numbers using the rand() function
• To be able to use pointers to pass arguments to functions using call-by reference.
• To understand the close relationships among pointers and arrays.
• To understand the use of pointers to functions.

Pointers
Pointers are variables that points to the locations of elements in the memory. They can be used
to point to variables as in the following code:

#include <iostream> // For std::cout

int main() {
int a; // a is an integer
int *aPtr; // aPtr is a pointer to an integer

a = 7;
aPtr = &a; // Assign the address of a to aPtr

// Output the address of 'a' and value of 'aPtr'


std::cout << "The address of a is " << &a << std::endl;
std::cout << "The value of aPtr is " << aPtr << std::endl;

// Output the value of 'a' and the value pointed to by 'aPtr'


std::cout << "The value of a is " << a << std::endl;
std::cout << "The value of (*aPtr) is " << (*aPtr) << std::endl;

// Showing that * and & are complements of each other


std::cout << "Showing that * and & are complements of each other" <<
std::endl;
std::cout << "(&*aPtr) = " << &*aPtr << std::endl;
std::cout << "(*&aPtr) = " << *&aPtr << std::endl;

return 0;
}

Pointers also can be used with array variables as in the following code:
#include <iostream>
int main() {
int Array[] = {4, 1, 87, -66, 2, -27};
int* ptr;
int i;
std::cout << "\n1) Show Array using array notation\n";
std::cout << "\t Element \t\tAddress of element\n";
std::cout << "\t--------------------------------------------------\n";
for (i = 0; i < 6; i++) {
std::cout << "\t Array[" << i << "] = " << Array[i] << "\t\t" <<
&Array[i] << '\n';
}

// Point our pointer to the first element of Array


ptr = Array; // equivalent to ptr = &Array[0]

std::cout << "\n2) Show Array using a pointer (ptr)\n";


std::cout << "\t Element \t\tAddress of element\n";
std::cout << "\t--------------------------------------------------\n";
for (i = 0; i < 6; i++) {
std::cout << "\t(*ptr) = " << (*ptr) << "\t\t" << ptr << '\n';
ptr++;
}
}

Activity 1
This program generates an array of random numbers between MIN and MAX using rand(). After
that, the program shifts the array of several PLACES to the right or to the left.

#include <iostream>
#include <cstdlib>
#include <ctime>

#define MaxSize 20
#define MIN 1
#define MAX 100
#define PLACES 3

void printArray(const int* array, int size);


void shiftArrayToRightBy(int array[], int size, int places);
void shiftArrayToLeftBy(int array[], int size, int places);

int randInRange(int min, int max) {


return min + std::rand() % (max - min + 1);
}

int main() {
int array[MaxSize];

std::srand(static_cast<unsigned>(std::time(nullptr))); // Seeding the


rand function to obtain various values

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


array[i] = randInRange(MIN, MAX); // Random between MIN and MAX
}
printArray(array, MaxSize); // Print array before shift

// Shift to left or right, uncomment what is needed


// shiftArrayToRightBy(array, MaxSize, PLACES);
// shiftArrayToLeftBy(array, MaxSize, PLACES);

printArray(array, MaxSize); // Print array after shift


}

Task 1.1: Define the function:


void printArray(int *s_ptr, int *e_ptr);
that prints the given array. The parameters are the starting address of the array (first element)
and the ending address of the array (last element).
Task 1.2: Define the function:
void shiftArrayToRightBy(int array[], int size, int places);
that shifts the given array to the right by a number of places.
Task 1.3: Define the function:
void shiftArrayToLeftBy (int array[], int size, int places);
that shifts the given array to the left by a number of places.
Task 1.4: change the program in activity 1 and let the user to choose in which direction is the
array should be shifted. Use the following new type of direction.
typedef char direction;
#define right ‘R’ || ‘r’
#define left ‘L’ || ‘l’

For example, if the user enters ‘R’ or ‘r’, that means the program should shift the array to the
right. Alternatively, ‘L’ or ‘l’ means the program should shift the array to the left.

Activity 2
Consider the following programs that randomly generate an integer array between 1 and 100
and then filter it and distinguish even and odd numbers in separate arrays. Note that, all
arrays must end with a zero.
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

#define MIN 1
#define MAX 100
#define LEN 10 // only 10 elements
// Function prototypes
void printArray(const int* arrayPtr);
int* generateArray(int min, int max, int length);
int* filterEvens(const int* arrayPtr);
int* filterOdds(const int* arrayPtr);

int main() {
// Generate random numbers between MIN and MAX
int* allNumbers = generateArray(MIN, MAX, LEN);

// Print the array


printArray(allNumbers);

// Generate even array by filtering allNumbers array and printing it


int* evenPtr = filterEvens(allNumbers);
printArray(evenPtr);

// Generate odd array by filtering allNumbers array and printing it


int* oddPtr = filterOdds(allNumbers);
printArray(oddPtr);

// Clean up dynamically allocated memory


delete[] allNumbers;
delete[] evenPtr;
delete[] oddPtr;

return 0;
}

void printArray(const int* arrayPtr) {


const int* loc = arrayPtr;
while (*loc != 0) { // Arrays should be terminated by zero value
cout << *loc << " ";
loc++; // Move to the next address
}
cout << endl;
}

Task 2.1: define the function


int * generateArray(int min, int max, int length){
that generates an array of random numbers between min and max with a specific length and
then returns the array (the pointer of the array). Since this is a function, the created array
must be allocated in the memory using malloc function. The array must be terminated by
zero (i.e., the value of last location must be zero).
Task 2.2: define the function
int * filterEvens(int * arrayPtr);
that takes a pointer to an array ‘arrayPtr’ and then generates a separate array of only even
numbers taken from the ‘arrayPtr’. The array must be generated dynamically using malloc.
The generated array must also be terminated by zero. The function must return the pointer of
the new array of locations.
Task 2.3: define the function
int * filterOdds(int * arrayPtr);
that takes a pointer to an array ‘arrayPtr’ and then generates a separate array of only odd
numbers taken from the ‘arrayPtr’. The array must be generated dynamically using malloc.
The generated array must also be terminated by zero. The function must return the pointer of
the new array of locations.

Activity 3
Indicate which lines of the following programs have errors?
#include <iostream>

using std::cout;
using std::endl;

void fun( const int * ); // prototype

int main()
{
int y;

fun( &y );

return 0;

} // end main

void fun( const int *xPtr )


{
*xPtr = 100;
}

Activity 4
Indicate which lines of the following programs have errors?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x, y;

int * const ptr = &x;


*ptr = 7;
ptr = &y;
return 0;
}

Activity 5
What will be the output for each of the following programs?
#include<iostream>
using namespace std;
int main() {
int x = 2;
int* ptrInt;

ptrInt = &x;
*ptrInt = 10;

cout << x << endl;

return 0;
}

Activity 6
Indicate which lines of the following programs have errors?
#include<iostream>
using namespace std;
int main() {
int m = 2, n = 3, result = 0;

int* ptrInt;
int* ptrResult;

ptrResult = &result;

ptrInt = &n;
*ptrResult += *ptrInt;

ptrInt = &m;
*ptrResult -= *ptrInt;

cout << "result : " << result << endl;

return 0;
}
Activity 7
Change the following program to use pass-by-reference instead of pass-by-value.
#include <iostream>
using std::cout;
using std::endl;

int cubeByValue( int ); // prototype

int main()
{
int number = 5;

cout << "The original value of number is " << number;

number = cubeByValue( number ); // pass number by value

cout << "\nThe new value of number is " << number << endl;
return 0;
} // end main

// calculate and return cube of integer argument


int cubeByValue( int n )
{
return n * n * n; // cube local variable n and return result
}

Activity 8
(Sum a Sequence of Integers) Write a C++ program that sums a sequence of integers.
Assume that the first integer read with (cin) specifies the number of values to be entered.
Your program should read only one value each time (cin) is executed. A typical input
sequence:

5 100 200 300 400 500

Where 5 indicates that the subsequent five values are to be summed.

Activity 9
(Find the Smallest) Write a C++ program that finds the smallest of several integers. Assume
that the first value read specifies the number of values remaining (as in task 4).

Activity 10
Using recursion, write a C++ program to find the following output:

1 2 4 8 16 32 64 64 32 16 8 4 2 1

Extra Task: (Time in Seconds) Write a function that takes the


time as three integer arguments (hours, minutes, and seconds) and returns the number of
seconds since the last time the clock struck 12. Use this function to calculate the amount of
time in seconds between two times, both of which are within one 12-hour cycle of the clock.
Lab 10: String handling functions

Objectives
• To be able to work with strings (array of characters)
• To be able to manipulate strings and use string helping functions (located in stdlib and
string header files)
◦ More about stdlib and string headers can be found at https://devdocs.io/c/
• To do basic problem solving of string manipulation

Activity 1
Consider the following incomplete program that converts a string of numbers to actual
numbers that are used to fill a given array.
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

// Function prototypes
int howManyNumbers(const string& str);
void print(const vector<int>& array);
void fillArray(vector<int>& array, const string& str);

int main() {
string str = "98 59 63 88 75";
int size = howManyNumbers(str);
vector<int> array(size); // Dynamic array using std::vector
fillArray(array, str);
print(array);
return 0;
}

Task 1.1: write the following function


int howManyNumbers(char * str);
that returns the count of the elements represented as a string in the argument ‘str’.
Task1.2: write the following function
void print(int array[], int size);
that prints the content of the array where the argument ‘size’ indicates the size or the length
of the array.
Task 1.3: write the following function
void fillArray(int array[], int size, char str[]);
that takes a string of numbers represented in the argument ‘str’ and then fills the array with
those numbers. Note that the argument size indicates the size of the array. You must use
utility helping functions to convert numbers from string representation to actual numbers
(e.g., use functions like ‘strtod’ or ‘atoi’).

Activity 2
Consider the following program that randomly generates an array of characters and then
filters it to distinguish strings of capital letters, small letters, numbers, and symbols using
separate functions. The challenging part of this activity is that you must use dynamic
allocation and call for all strings.
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <ctime>

using namespace std;

/* Function prototypes */
void printElements(const string& str);
string generateString(int min, int max, int length);
string filterCapitalLetters(const string& str);
string filterSmallLetters(const string& str);
string filterNumbers(const string& str);
string filterSymbols(const string& str);

int main() {
// Generate a random string between min and max with length
string str = generateString(32, 126, 50);
// Print it
printElements(str);
// Filter capital letters
string capLetters = filterCapitalLetters(str);
printElements(capLetters);
// Filter small letters
string smallLetters = filterSmallLetters(str);
printElements(smallLetters);
// Filter numbers
string numbersStr = filterNumbers(str);
printElements(numbersStr);
// Filter symbols
string symbolsStr = filterSymbols(str);
printElements(symbolsStr);
return 0;
}

void printElements(const string& str) {


if (str.empty()) return;
for (char c : str) {
cout << c << ' ';
}
cout << endl;
}

Task2.1: define the function


char * generateString(int min, int max, int length);
that generates randomly a sequence of characters between 'min' and 'max' for the given length
from the ASCII code. Not that, you need to use dynamically created string. For that, we use
the malloc function as follows:
char * myString = (char *) malloc(sizeof(char) * length);
We also need to use the rand function to generate random characters from ASCII code
(according to 'min' and 'max') as follows:
myString[index++] = min + ( rand() % (max - min + 1) );

Task 2.2: define the function


char * filterCapitalLetters(const string& str);
that iterates through the string to generate a new string of only capital alphabetic letters.
Again, you must use dynamic array allocation to be able to return the generated array as
follows:
// initially start with 1 and increase the allocation if needed
char * filter = (char *) malloc(sizeof(char) * 1);
If more capital alphabets were found, we re-allocate the variable 'filter' and preserve more
space as follows:
filter = (char *) realloc(filter, sizeof(char) * index);
where 'index' is the counter variable that increases whenever a new capital letter is found.
Remember that the 'string' variable is a pointer and to iterate you follow the same tactics that
are used in the 'printElements' function in the given code. Also, we must use the function
isupper that is in the ctype header file to distinguish the desired alphabets as follows:

while(*cPtr != '\0') {
if(isupper(*cPtr) != 0) {
filter[index++] = *cPtr;
filter = (char *) realloc(filter, sizeof(char) * index);
...

Task 2.3: define the function


char * filterSmallLetters(const string& str);
that does almost the same as Task 2.2 but it generates a new string of only small alphabetic
letters. To differentiate the letters of the small alphabets, we use the function islower which
is also in the ctype header file.
Task 2.4: define the function
char * filterNumbers(const string& str);
that does again the same as Task 2.2 and 2.3 but it generates a new string of only numbers.
To distinguish the digits, we use the function isdigit which is also in the ctype header file.
Task 2.5: define the function
char * filterSymbols(const string& str);
that generates a new string of only symbols from the original string and returns it. To
distinguish symbols characters, we negate the positive result of calling the function isalnum
in cctype header file which returns 1 if the given character is an alphanumeric character.
That is, if the character is not alphanumeric, then it must be a symbol.
Lab 11: Structure (part 1)

Objectives
• To be able to create and use structures.
• To be able to understand struct notation.
• Use helpful string handling functions such as strcpy() and strcmp
Use (https://devdocs.io/cpp/) and search for any function you want.
• To understand how to convert strings to numerical representations, like strtof() etc.
See conversion functions at (https://devdocs.io/cpp/string/byte) for more.
• To be able to use structures with functions.

Structures
Structures are notations to define container variables -- a single variable that can have any
number of members (inside variables) of different types. For example, the following is a
structure:
#include <iostream>
#include <string>

using namespace std;

// Define the struct (class in C++ is similar, but we use struct here for
consistency)
struct Table {
int width;
int height;
int depth;
string color; // Use std::string instead of char array
};

// Function prototypes
void myFunction(const Table& inTable);

int main() {
// Using the struct
Table tableVar1;
// Initialize while declaring
Table tableVar2 = {150, 100, 70, "Gray"};

// Access members of struct using dot operator


if (tableVar2.depth > 100) {
cout << "Not standard height!" << endl;
}

// Get input for tableVar1's height


cout << "Enter a value for height: ";
cin >> tableVar1.height;
// Call function passing tableVar2
myFunction(tableVar2);

return 0;
}

void myFunction(const Table& inTable) {


// Function implementation
// Just printing the values for demonstration
cout << "Table dimensions and color in function:" << endl;
cout << "Width: " << inTable.width << endl;
cout << "Height: " << inTable.height << endl;
cout << "Depth: " << inTable.depth << endl;
cout << "Color: " << inTable.color << endl;
}

Activity 1
Given the following structure and the main function prints the value of a one struct pixel
variable:
#include <iostream>
using namespace std;
struct Pixel {
double x, y;
};

void printStructure(const Pixel& pVar); // Pass by reference to avoid copying


int main() {
Pixel p = {512.732, 200.53}; // Initialize the structure
printStructure(p); // Calling function and passing the variable p
return 0;
}

Task1.1: define the function


void printStructure(struct Pixel pVar);

That prints the values of all members of the struct Pixel.

Activity 2
Given the following structure and the main function that prints the values of 5 students
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

struct Student {
string fName;
string lName;
string sId;
};

// Function prototypes
Student createStudent();
Student createStudentByString(const string& input, char delimiter);

int main() {
// Entering details of student 1 using separate inputs
cout << "Please enter student 1 details: " << endl;
Student s1 = createStudent();
cout << "Student 1 details: " << s1.fName << " " << s1.lName << ", ID = "
<< s1.sId << endl;

// Entering details of student 2 using a single long string


cout << "Please enter student 2 details (separated with a non-space
delimiter) as a long string:" << endl;

string input;
cin.ignore(); // Clear the input buffer
getline(cin, input); // Read the entire line of input

char delimiter;
cout << "Please enter the delimiter character (non-space): ";
cin >> delimiter;

// Split the string according to the delimiter


Student s2 = createStudentByString(input, delimiter);

// Print the new student


cout << "Student 2 details: " << s2.fName << " " << s2.lName << ", ID = "
<< s2.sId << endl;
return 0;
}

Task2.1: define the function


Student createStudent();
That creates a new instance of struct Student and returns it. The values for struct Student are
asked to be entered by the user using the function scanf().
Task 2.2: define the function
Student createStudentByString(char string[], int length, char *delimiter);
That creates a new instance of struct Student from a given string and returns it. The function
receives the long string, its length and the delimiter (as a string/array of one character) that
can be used to split the long string and get the values of the struct.
For example, if the user enters “Ali;Khalid;123” for the string, and enters ‘;’ for the
delimiter, then the function read “Ali”, “Khalid”, “123” as separate values.
This task can be done in two ways, one way is to loop the string and read for a value until
you reach the delimiter and then copy that to the target structure member. Another way is to
use strtok which splits the string with the delimiter.
Helping functions that you can use for this function are: strcpy (allows you to copy strings
from source to destination) and strtok (splits a given string into tokens). See the examples in
on (https://devdocs.io/cpp/string/byte ). You can use the search box to search for any
function you want.
Lab 12: Structure (part 2)
Objectives
• To be able to create and use structures
• To be able to understand struct notation and pointer notation
• Use strcpy to copy a string from source to destination
• To able to understand how to divide a string into tokens using strtok
• To be able to pass structures to functions called by value and call by reference.
• Search about strcpy and strtok functions at (https://devdocs.io/c/)

Activity 1
This program firstly initializes an object of struct Circle with values and then updates those
using pointers. The program uses structure notation once and pointer notation another
afterwards.
#include <iostream>
#include <cstdlib>
#include <ctime>

#define MIN 1
#define MAX 30

struct Circle {
float xCoord;
float yCoord;
float radius;
};

// Function prototypes
float getRandomNumber(int min, int max);
void printByValue(const Circle& cirObj);
void setValue(float& target, float newValue);
void printByReference(const Circle& cirObj);

int main() {
// Seed the random number generator
std::srand(static_cast<unsigned>(std::time(nullptr)));

// Declare a struct Circle and name it circleObject


Circle circleObject;

// Fill circleObject's members with random numbers


circleObject.xCoord = getRandomNumber(MIN, MAX);
circleObject.yCoord = getRandomNumber(MIN, MAX);
circleObject.radius = getRandomNumber(MIN, MAX);

// Printing values of the circle by calling function printByValue


printByValue(circleObject);
// Update values of circle one by one
setValue(circleObject.xCoord, getRandomNumber(MIN, MAX));
setValue(circleObject.yCoord, getRandomNumber(MIN, MAX));
setValue(circleObject.radius, getRandomNumber(MIN, MAX));

// Printing values after update by calling function printByReference


printByReference(circleObject);

return 0;
}

Task1.1: define the function


float getRandomNumber(int min, int max);
that returns a random number generated within the range min and max.
Task1.2: define the function
void printByValue(struct Circle cirObj);
that prints on the screen values of circle (xCoord, yCoord, and radius).
Task1.3: define the function
void setValue(float *target, float newValue);
that updates the given variable var with the new value. Use this to update the value of circle
object in the activity. For example, call it to update values of xCoord, yCoord, and radius.
Task1.4: define the function
void printByReference(struct Circle *cirObj);
that prints on the screen the values of circle object after using the function in Task1.3 above
but with call by reference (pointer of circle).

Activity 2
The following program asks the user to enter full name of a person (first, middle and last name)
and prints the person's initials. The full name must be split by space character (‘ ’) and then fill
a variable of type Person with values given from the string.
#include <iostream>
#include <string>

struct Person {
std::string firstName;
std::string middleName;
std::string lastName;
};

// Function prototypes (definitions are not provided)


void updatePerson(Person* pPtr, const std::string& fullName);
void printPersonInitials(const Person* pPtr);

int main() {
Person personObject;
std::string fullName;

std::cout << "Enter person's full name: ";


std::getline(std::cin, fullName);

updatePerson(&personObject, fullName);

std::cout << "First Name: " << personObject.firstName


<< ", Middle Name: " << personObject.middleName
<< ", Last Name: " << personObject.lastName
<< std::endl << std::endl;

printPersonInitials(&personObject);

return 0;
}

Task 2.1: define the function


void updatePerson(Person *pPtr, char string[], int stringSize);
that update the content of a struct person with values obtained from a given string. The values
are separated by a space character.

Task 2.2: Define the function


void printPersonInitials(Person *pPtr)
This function must print the initials of a given person’s full name. The initial is a first letter of
a name. For example, if the person’s full name is “Mohammad Khalid Almohammad”, then
the initials would be: M. K. A.

Activity 3
The following program reads three students' records and creates an array of structures of the
students. Information of the records is organized as follows:
{student id, student name, student date of birth, city of birth}

For example, the following are examples of student records:


“17581726”, “Mohammad Al-Abdullah”, “2002-12-10”, “Buraydah”
“55382214”, “Ibrahim Al-Faris”, “2003-05-07”, “Riyadh”

#include <iostream>
#include <string>

struct Student {
std::string id;
std::string name;
std::string ddmmyyyy;
std::string cityBirth;
};

// Function prototypes (definitions are not provided)


void fillStruct(Student* std, const std::string currentStd[4]);

int main() {
const std::string records[3][4] = {
{"17581726", "Mohammad Alabdullah", "2002-12-10", "Buraydah"},
{"55382214", "Ibrahim Alfaris", "2003-05-07", "Riyadh"},
{"62111622", "Ahmad Almansor", "2001-02-22", "Buraydah"}
};

Student students[3];

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


fillStruct(&students[i], records[i]);
}

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


std::cout << "Student Name: " << students[i].name << ", ";
std::cout << "Student ID: " << students[i].id << ", ";
std::cout << "DOB: " << students[i].ddmmyyyy << ", ";
std::cout << "City of DOB: " << students[i].cityBirth << std::endl;
}

return 0;
}

// Function definitions
void fillStruct(Student* std, const std::string currentStd[4]) {
std->id = currentStd[0];
std->name = currentStd[1];
std->ddmmyyyy = currentStd[2];
std->cityBirth = currentStd[3];
}

Task3.1: the program above calls the function fillStruct and provides as arguments one
record entry of a student and a pointer of a struct. The function must fill the struct with
information from the record. However, for the date entry, the date is provided in a format that
needs to be changed: instead of YYYY-MM-DD the date should be filled in the struct as DD-
MM-YYYY.
Define the function that does the above task
void fillStruct(struct studentStruct *std, char currentStd[4][50]);
Lab 13: Structure (part 3)

Objectives
• To be able to create and use structures.
• To be able to pass structures to functions by value and by reference.

Activity 1
In this lab session, you are going to improve a simulator for an air conditioner. Users can select
sort of actions that the air conditioner allows. The actions are
1. Turn air conditioner On/Off
2. Increase fan speed by 100
3. Decrease fan speed by 100
4. Change to mode of cooling: On/Off
5. Increment the temperature degree of the air conditioner
6. Decrement the temperature degree of the air conditioner
7. Exit the program

#include <iostream>

#define MinFan 100


#define MaxFan 1000
#define MinCool 18
#define MaxCool 30

typedef struct AirConditionerStruct {


bool status; // running status
struct FanStruct {
bool flow;
int fanSpeed;
} fanControl;

struct ModeStruct {
bool cooling;
int degree;
} coolingControl;
} AirConditioner;

/* Prototypes */
void changeStatus(AirConditioner* airPtr);
void increaseFanSpeed(AirConditioner* airPtr, int maxLimit);
void decreaseFanSpeed(AirConditioner* airPtr, int minLimit);
void changeMode(AirConditioner* airPtr);
void incrementDegree(AirConditioner* airPtr, int maxLimit);
void decrementDegree(AirConditioner* airPtr, int minLimit);
void printAirConditionerStatus(const AirConditioner* airPtr);

int main() {
bool exit = false;
int choice;
AirConditioner airCondObject = {false, {false, MinFan}, {false,
MinCool}};

while (!exit) {
std::cout << "\n----------------\n";
std::cout << "1) Turn air conditioner ON/OFF?\n";
std::cout << "2) Increase air conditioner fan?\n";
std::cout << "3) Decrease air conditioner fan?\n";
std::cout << "4) Change air conditioner mode?\n";
std::cout << "5) Increment temperature degree?\n";
std::cout << "6) Decrement temperature degree?\n";
std::cout << "7) Exit..!\n";
std::cin >> choice;

switch (choice) {
case 1: changeStatus(&airCondObject); break;
case 2: increaseFanSpeed(&airCondObject, MaxFan); break;
case 3: decreaseFanSpeed(&airCondObject, MinFan); break;
case 4: changeMode(&airCondObject); break;
case 5: incrementDegree(&airCondObject, MaxCool); break;
case 6: decrementDegree(&airCondObject, MinCool); break;
case 7: exit = true; break;
default: std::cout << "Invalid selection of option. Try
again!\n";
}
if (!exit) {
printAirConditionerStatus(&airCondObject);
}
}

return 0;
}

void printAirConditionerStatus(const AirConditioner* airPtr) {


std::cout << "\nAir conditioner status: " << (airPtr->status ?

Task 1.1: Define the function:


void changeStatus(AirConditioner *airPtr)
That turns the air conditioner ON or OFF according to the following conditions:
• If the air conditioner is in standby mode, then the function sets the running status to
ON, enables the fan flow, and puts the fan speed to the minimum. Also, the mode
cooling system must be set ON.
If the air conditioner is on running mode, then the function sets the running status to OFF and
the air condition fan flow to OFF. The cooling mode must also be put to OFF.
Task 1.2: Define the function:
void increaseFanSpeed(AirConditioner *airPtr, int maxLimit)
The function does the following.
• If the running status of the air conditioner is ON, then increase the air conditioner fan
speed by 100 if and only if the result fan speed is below maxLimit. If the air conditioner
fan speed was about to exceed the maxLimit, then display the following message:

“The air conditioner fan speed has reached the maximum limit.”
If the running status of the air conditioner is OFF, then display the following message:

"The air conditioner is OFF."

Task 1.3: Define the function:


void decreaseFanSpeed(AirConditioner *airPtr, int minLimit)
The function does the following.
• If the running status of the air conditioner is ON, then decrease the air conditioner fan
speed by 100 if and only if the result fan speed is above minLimit. If the air conditioner
fan speed was about to be below minLimit, then display the following message:

“The air conditioner fan speed has reached the minimum limit.”
• If the running status of the air conditioner is OFF, then display the following message:

"The air conditioner is OFF."

Task 1.4: Define the function


void changeMode(AirConditioner *airPtr);
that changes the cooling mode of the air conditioner to ON or OFF according to the following
conditions:
• If the running status of an air conditioner is ON and the cooling status is also ON, then
put the air condition cooling status to OFF.
• If the running status of the air conditioner is ON and the cooling status is OFF, then put
the air condition cooling status to ON.
• If the running status of the air conditioner is OFF, then display the following message:
"The air conditioner is OFF."

Task 1.5: Define the function


void incrementDegree(AirConditioner *airPtr, int maxLimit)
that increment the temperature degree of the air conditioner by 1 unit if and only if the running
status of the air conditioner is ON and the result temperature degree doesn’t exceed the
maximum limit of the temperature. Otherwise, display the following message:
“The air conditioner cooling temperature has reached the maximum limit.”
If the running status of the air conditioner is OFF, then display the following message:
"The air conditioner is OFF."

Task 1.6: Define the function


void decrementDegree(AirConditioner *airPtr, int minLimit)
that decrement the temperature degree of the air conditioner by 1 unit if and only if the running
status of the air conditioner is ON and the result temperature degree doesn’t go below the
minimum limit of the temperature. Otherwise, display the following message:
“The air conditioner cooling temperature has reached the minimum limit.”
If the running status of the air conditioner is OFF, then display the following message:
"The air conditioner is OFF."
Lab 14: Files Processing

Lab Objectives
• To understand Files I/O.
• To be able to write and read from files.
• Finding unacceptable behaviours using simple test cases
• Understand software corrections.

Activity 1
Create a text file named "input.txt" with the following content:

10 20 30 40 50

Write a C program to read these numbers from the file, calculate their sum, and write the sum
to another file named "output.txt".

Activity 2
Create a text file named "names.txt" with the following content:

Ali
Charlie
Bob
David
Saleh

Write a program to read these names from the file, sort them alphabetically, and write the
sorted names to another file named "sorted_names.txt."

Activity 3
Write a program that creates a file named "data.txt" and writes the numbers 1 to 10 to this
file, each on a new line. Open the "data.txt" file again, read the numbers, and print them to
the console.

Challenge
Create a text file named "text_input.txt" with the following content:

Hello world! This is a simple world. World, hello!


Write a program to read the text from the file, count the occurrences of each word, and write
the word count to another file named "word_count_output.txt."
Lab 15: Bitwise Operators, Enumeration and Union

Objectives
To be able to use bitwise operators.
To be able to understand bitwise operators.
Use (https://devdocs.io/cpp/) and search for any function you want.
To be able to use union and enumeration.

Activity 1
Write a program that uses bitwise operators to perform basic operations on binary
representations of numbers given the following instructors:
Define two integers then perform operators AND, OR, XOR, NOT, and Left and Right shift.

Activity 2
Write a program that uses enumeration to represent days of the week. If user enter
Wedensday, the program responds, “it is a working day.”

Activity 3
Write a program that uses union to represent a variable to store integer or float number. The
user then assigns a value to an integer then prints the value of all union members. Repeat the
same for float.

You might also like