181 Lab v2.1
181 Lab v2.1
College of Computer
Computer Science Department
Laboratory Booklet
for
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
#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
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;
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;
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
int main() {
double total = 0.0, grade = 0.0;
int counter = 1;
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
int main() {
double total = 0.0;
int counter = 0;
double grade = 0.0;
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.
+
+
++*++
+
+
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
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
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
int main() {
int min, max, sum = 0;
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;
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;
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
// 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++ ){
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;
}
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;
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.
#include <iostream>
using namespace std;
inline int add(int a, int b) {
return a + b;
}
int main() {
cout<<add(3, 5);
return 0;
}
#include <iostream>
using namespace std;
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;
}
#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;
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;
}
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.
// Function prototypes
int sumAllEven(const int rand_array[], int array_size);
int main() {
int myArray[SIZE];
generateArray(myArray, SIZE, MIN, MAX);
std::cout << "The sum is " << sumAllEven(myArray, SIZE) << std::endl;
return 0;
}
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.
// 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 << "There are " << count << " of the symbol " << target << " exist."
<< endl;
return 0;
}
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
// Function prototypes
int countParks(const char street[], int size);
void fillStreet(char street[], int size);
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;
}
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
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
// Function prototype
int longestFence(const char input[], int size);
int main() {
char string[MAX];
char c;
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,
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:
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
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';
}
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
int main() {
int array[MaxSize];
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>
#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);
return 0;
}
Activity 3
Indicate which lines of the following programs have errors?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int y;
fun( &y );
return 0;
} // end main
Activity 4
Indicate which lines of the following programs have errors?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x, y;
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;
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;
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 main()
{
int number = 5;
cout << "\nThe new value of number is " << number << endl;
return 0;
} // end main
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:
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
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>
// 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;
}
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>
/* 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;
}
while(*cPtr != '\0') {
if(isupper(*cPtr) != 0) {
filter[index++] = *cPtr;
filter = (char *) realloc(filter, sizeof(char) * index);
...
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>
// 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"};
return 0;
}
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;
};
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;
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;
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)));
return 0;
}
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;
};
int main() {
Person personObject;
std::string fullName;
updatePerson(&personObject, fullName);
printPersonInitials(&personObject);
return 0;
}
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}
#include <iostream>
#include <string>
struct Student {
std::string id;
std::string name;
std::string ddmmyyyy;
std::string cityBirth;
};
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];
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>
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;
}
“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 fan speed has reached the minimum limit.”
• If the running status of the air conditioner is OFF, then display the following message:
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:
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.