COS 102 Practical
COS 102 Practical
Course Content:
Problem solving strategies, Concepts and properties of Algorithms, Role of algorithm in problem
solving process, Characteristics of good algorithms, Steps involved in algorithm development,
Problem solving strategies: top down and bottom-up methods, Implementation strategies, Develop
algorithms for simple problems, Representation of algorithms: Flowchart and Pseudocodes,
Development of flowchart and pseudocodes, Flowchart symbols and uses, Program objects,
Implementation of algorithm in any programming language such as Visual Basic, Java, C or C++
By
1
1.1Problem Solving Using Algorithm and
Flowchart
Dr. Adaora Obayi
The following Examples illustrate problem solving through the development of Algorithms.
Example 1 Develop an algorithm in pseudo-code that ask the user for two integer values and compute and
displays their sum and product.
1. Request Data
1.1 Request X
1.2 Request Y
2. Process/Calculate Results
2.1 Calculate total = X+Y
2.2 Calculate product = X*Y
3. Display Results
3.1 Display total
3.2 Display product
Example 2. Develop an algorithm in pseudo code that will read in the width and length of a rectangular
plot in feet, and the price per square foot, the algorithm will compute and display the total price of the plot.
1. Request Data
1.1 Request Length
1.2 Request width
1.3 Request Unit_Price
2. Calculate Total Price
2.1 Calculate Area = Length*Width
2.2 Calculate Total_Price = Area*Unit_Price
3. Display Total Price
2
Example 3 Develop an algorithm in pseudo code that will request for the following as input: age of staff,
normal pay rate per hour, number of hours worked, and the algorithm will calculate the pay as follows:
If the age of the staff is less than eighteen years, the pay rate will be 2/3 of the normal pay rate; otherwise,
the normal pay rate will be used.
Solution:
From the above problem, we can identify the following steps that sole the problem:
1. Request Data
2. Calculate Pay
3. Display Pay
Applying stepwise refinement to each of the steps where necessary, we have the following refinements:
1. Request Data
1.1 Request age
1.2 Request pay rate
1.3 Request hours
2. Calculate Pay
2.1 IF age ‹ 18 THEN
2.1.1 Calculate pay = 2/3*pay rate*hours ELSE
2.1.2 Calculate pay = pay rate*hours
3. Display Pay
Example 4: Develop an algorithm in pseudo code that will request for an integer number of students,
afterwards, it will request for score of each of the students and it will calculate and display the total score.
1. Request n
2. Calculate total
2.1 Calculate count = 0
2.2 Calculate total = 0
2.3 Calculate count = count + 1
2.4 Request score
2.5 Calculate total = total + score
2.6 Repeat 2.3, 2.4, 2.5 until count = n
3. Display total
Example 5: Develop an algorithm in pseudo code that will request for an integer number, as the number of
students, afterwards, it will request for an n different scores and it will determine and display the minimum
of the scores.
1. Request n
2. Determine minimum
2.1 Initialize count = 1
2.2 Request score
2.3 Initialize minimum score = score
2.4 Calculate count = count + 1
2.5 Request score
2.6 Calculate minimum = score IF score ‹ minimum
2.7 Repeat 2.4, 2.5, 2.6 until count = n
3. Display minimum
Example 6: Write an algorithm to calculate the simple interest using the formula:
3
Simple Interest = 𝑃 ∗ 𝑁 ∗ 𝑅 /100, Where 𝑃 is principle Amount, 𝑁 is the number of years and 𝑅 is the rate
of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2: Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.
Example 10: Write an algorithm which will test whether a given integer value is prime or not.
Algorithm to test for Prime
Step 1: M = 2
Step 2: read N
Step 3: MAX = SQRT (N)
Step 4: While M < = MAX do
4.1 If (M * (N/M) = N then
4.1.1 Goto step 7
Step 4.2. M = M+1
Step 5: Write “number is prime”
Step 6 Goto step 8
Step 7 Write “number is not a prime”
4
Step 8 End
Example 12: Write an algorithm to calculate the perimeter and area of rectangle. Given its length and
width.
Step 1: Read length and width of the rectangle
Step 2: Calculate perimeter = 2* (length + width)
Step 3: Calculate area = length *width.
Step 4: Print perimeter
Step 5 Print area
Step 6: Stop
C++ gives programmers a high level of control over system resources and memory.
The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14,
C++17, C++20.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
5
C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.
C++ was developed as an extension of C, and both languages have almost the same syntax.
The main difference between C and C++ is that C++ support classes and objects, while C does
not.
There are many text editors and compilers to choose from. In this tutorial, we will use an IDE
(see below).
An IDE (Integrated Development Environment) is used to edit AND compile the code.
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can
be used to both edit and debug C++ code.
We will use Code::Blocks in our tutorial, which we believe is a good place to start.
6
You can make programming fun by making the C++ Compiler handy. You can install a version of
C++ Compiler on your Android phone. This can be done by going to Play Store, search for C++
Compiler, a list of different C++ Compiler will appear. Choose one, I have chosen Coding C++,
and install it on your Android phone. Coding can then start with you Android phone.
C++ Quickstart
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters.
For now, focus on how to run the code.
Then, go to Build > Build and Run to run (execute) the program. The result will look something
to this:
7
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
Example explained
Line 1: #include <iostream> is a header file library that lets us work with input and output
objects, such as cout (used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the
standard library.
Don't worry if you don't understand how #include <iostream> and using namespace std works.
Just think of it as something that (almost) always appears in your program.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<)
to output/print text. In our example it will output "Hello World".
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main function.
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:
#include <iostream>
8
int main() {
std::cout << "Hello World!";
return 0;
}
The cout object, together with the << operator, is used to output values/print text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line
at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line
at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
9
return 0;
}
New Lines
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
10
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.
Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
// This is a comment
cout << "Hello World!";
Example
cout << "Hello World!"; // This is a comment
It is up to you which you want to use. Normally, we use // for short comments, and /* */ for
longer.
C++ Variables
In C++, there are different types of variables (defined with different keywords), for example:
11
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
• string - stores text, such as "Hello World". String values are surrounded by double quotes
• bool - stores values with two states: true or false
Syntax
type variableName = value;
Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
12
Other Types
Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
You will learn more about the individual types in the Data Types chapter.
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Example
int myAge = 35;
cout << "I am " << myAge << " years old.";
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
13
Exercise:
To declare more than one variable of the same type, use a comma-separated list:
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;
C++ Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Example
// Good
int minutesPerHour = 60;
14
int m = 60;
Constants
When you do not want others (or yourself) to override existing variable values, use
the const keyword (this will declare the variable as "constant", which means unchangeable and
read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are unlikely to
change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
You have already learned that cout is used to output (print) values. Now we will use cin to get
user input.
cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
In the following example, the user can input a number, which is stored in the variable x. Then we
print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
15
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
In this example, the user must input two numbers. Then we print the sum by calculating (adding)
the two numbers:
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Exercise:
Use the correct keyword to get user input, stored in the variable x:
As explained in the Variables chapter, a variable in C++ must be a specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
16
Try it Yourself »
The data type specifies the size and type of information the variable will store:
Float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits
Double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits
You will learn more about the individual data types in the next chapters.
Exercise:
myNum = 9;
myDoubleNum = 8.99;
myLetter = 'A';
myBool = false;
17
myText = "Hello World";
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Boolean Types
A boolean data type is declared with the bool keyword and can only take the values true or false.
18
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing, which you will learn more about in a
later chapter.
Character Types
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
char myGrade = 'B';
cout << myGrade;
Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
String Types
The string type is used to store a sequence of characters (text). This is not a built-in type, but it
behaves like one in its most basic usage. String values must be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in the source code,
the <string> library:
19
Example
// Include the string library
#include <string>
C++ Operators
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Try it Yourself »
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Try it Yourself »
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic Operators
20
Arithmetic operators are used to perform common mathematical operations.
Exercise:
cout << 10 5;
Assignment Operators
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
21
Example
int x = 10;
Try it Yourself »
Example
int x = 10;
x += 5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
22
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
Try it Yourself »
== Equal to x == y
!= Not equal x != y
23
> Greater than x>y
Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
C++ Strings
Example
24
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
// Include the string library
#include <string>
C++ Exercises
Test Yourself With Exercises
Exercise:
Fill in the missing part to create a greeting variable of type string and assign it the value Hello.
= ;
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
In the example above, we added a space after firstName to create a space between John and Doe
on output. However, you could also add a space with quotes (" " or ' '):
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
Append
25
A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, you can also concatenate strings with the append() function:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
WARNING!
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
Example
string x = "10";
int y = 20;
string z = x + y;
String Length
26
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
Tip: You might see some C++ programs that use the size() function to get the length of a string.
This is just an alias of length(). It is completely up to you if you want to use length() or size():
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
Access Strings
You can access the characters in a string by referring to its index number inside square
brackets [].
Example
string myString = "Hello";
cout << myString[0];
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
Example
string myString = "Hello";
cout << myString[1];
// Outputs e
To change the value of a specific character in a string, refer to the index number, and use single
quotes:
Example
string myString = "Hello";
myString[0] = 'J';
cout << myString;
27
// Outputs Jello instead of Hello
It is possible to use the extraction operator >> on cin to display a string entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
From the example above, you would expect the program to print "John Doe", but it only prints
"John".
That's why, when working with strings, we often use the getline() function to read a line of text.
It takes cin as the first parameter, and the string variable as second:
Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
28
// Type your full name: John Doe
// Your name is: John Doe
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for string (and cout) objects:
Example
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
C++ Math
C++ has many functions that allows you to perform mathematical tasks on numbers.
The max(x,y) function can be used to find the highest value of x and y:
Example
cout << max(5, 10);
Try it Yourself »
And the min(x,y) function can be used to find the lowest value of x and y:
29
Example
cout << min(5, 10);
Try it Yourself »
Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm),
can be found in the <cmath> header file:
Example
// Include the cmath library
#include <cmath>
A list of other popular Math functions (from the <cmath> library) can be found in the table
below:
Function Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x
asin(x) Returns the arcsine of x
30
expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y
C++ Exercises
Test Yourself With Exercises
Exercise:
int x = 5;
int y = 10;
cout << (x, y);
C++ Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
• YES / NO
• ON / OFF
• TRUE / FALSE
31
For this, C++ has a bool data type, which can take the values true (1) or false (0).
Boolean Values
A boolean variable is declared with the bool keyword and can only take the values true or false:
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
From the example above, you can read that a true value returns 1, and false returns 0.
However, it is more common to return boolean values from boolean expressions (see next page).
Boolean Expression
A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).
You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:
Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
Try it Yourself »
Or even easier:
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
Try it Yourself »
In the examples below, we use the equal to (==) operator to evaluate an expression:
Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
32
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
Booleans are the basis for all C++ comparisons and conditions.
You will learn more about conditions (if...else) in the next chapter.
C++ Exercises
self With Exercises
Exercise:
Fill in the missing parts to print the values 1 (for true) and 0 (for false):
isCodingFun = true;
isFishTasty = false;
cout << ;
cout << ;
C++ Conditions and If Statements
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
33
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition
is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using
the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the
screen that "x is greater than y".
C++ Exercises
Test Yourself With Exercises
Exercise:
int x = 50;
int y = 10;
34
(x y) {
cout << "Hello World";
}Bottom of Form
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we
move on to the else condition and print to the screen "Good evening". If the time was less than
18, the program would print "Good day".
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
35
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next
condition, in the else if statement, is also false, so we move on to the else condition
since condition1 and condition2 is both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often used
to replace simple if else statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
36
} else {
cout << "Good evening.";
}
Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
37
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
38
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
Note: The default keyword must be used as the last statement in the switch, and it does not need
a break
C++ Exercises
Test Yourself With Exercises
Exercise:
int day = 2;
switch ( ){
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
}
C++ Loops
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
39
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i)
is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never
end!
C++ Exercises
Tesself With Exercises
Exercise:
int i = 1;
(i < 6) {
cout << i << "\n";
;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do {
// code block to be executed
40
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
41
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is
true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
C++ Exercises
Test Yourself With Exercises
Exercise:
Use a for loop to print "Yes" 5 times:
(int i = 0; i < 5; ) {
cout << << "\n";
}
C++ Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
42
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
Continue Example
int i = 0;
while (i < 10) {
43
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
C++ Exercises
Test Yourself With Exercises
Exercise:
Stop the loop if i is 5:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Hello World!
Try it Yourself »
44
Online C++ Compiler Explained
The window to the left is editable - edit the code and click on the "Run" button to view the result
in the right window.
Icon No Description
1 Go to www.w3schools.com
After editing the C++ code, just click Run to execute the C++ code.
C++ Exercise:
1. Insert the missing part of the code below to output "Hello World!".
int main() {
<< "Hello World!";
return 0;
}
45
int main() {
cout << "Hello World! ";
cout << "I am learning C++";
return 0;
}
3. Comments in C++ are written with special characters. Insert the missing parts:
= ;
= ;
int y = 10;
cout << x + y;
int x = 5;
int y = 10;
= x + y;
cout << ;
46
7. Fill in the missing parts to create three variables of the same type, using a comma-
separated list:
x = 5 y = 6 z = 50;
cout << x + y + z;
8. Use the correct keyword to get user input, stored in the variable x:
int x;
cout << "Type a number: ";
>> ;
9. Fill in the missing parts to print the sum of two numbers (which is put in by the user):
int x, y;
int sum;
cout << "Type a number: ";
>> ;
cout << "Type another number: ";
>> ;
sum = x + y;
cout << "Sum is: " << ;
10. Add the correct data type for the following variables:
myNum = 9;
myDoubleNum = 8.99;
myLetter = 'A';
myBool = false;
47
myText = "Hello World";
11. Create two boolean variables, named yay and nay, and add appropriate values to them:
= ;
= ;
= "Hello";
cout << ;
cout << 10 5;
cout << 10 5;
15. Use the correct operator to increase the value of the variable x by 1.
int x = 10;
x;
16. Use the correct operator to increase the value of the variable x by 1.
48
int x = 10;
x;
17. Fill in the missing part to create a greeting variable of type string and assign it the
value Hello.
= ;
19. Use the correct function to print the length of the txt string.
20. Access the first character (H) in myString and print the result:
49
cout << myString;
22. Use the correct function to print the highest value of x and y.
int x = 5;
int y = 10;
cout << (x, y);
#include <iostream>
#include < >
using namespace std;
int main() {
int x = 64;
cout << (x);
return 0;
}
24. Use the correct function to round the number 2.6 to its nearest integer.
#include <iostream>
#include < >
using namespace std;
int main() {
cout << (2.6);
return 0;
50
}
25. Fill in the missing parts to print the values 1 (for true) and 0 (for false):
isCodingFun = true;
isFishTasty = false;
cout << ;
cout << ;
26. Fill in the missing parts to print the value true (for true):
int x = 10;
int y = 9;
cout << ( );
int x = 50;
int y = 10;
(x y) {
cout << "Hello World";
}
int x = 50;
int y = 50;
(x y) {
51
cout << "Hello World";
}
int x = 50;
int y = 50;
(x y) {
cout << "Yes";
} {
cout << "No";
}
30. Print "1" if x is equal to y, print "2" if x is greater than y, otherwise print "3".
int x = 50;
int y = 50;
(x y) {
cout << "1";
} (x y) {
cout << "2";
} {
cout << "3";
}
31. Insert the missing parts to complete the following "short hand if...else statement"
(ternary operator):
52
string result = time < 18 "Good day."
"Good evening.";
cout << result;
32. Insert the missing parts to complete the following switch statement.
int day = 2;
switch ( ) {
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
}
33. Complete the switch statement, and add the correct keyword at the end to specify
some code to run if there is no case match in the switch statement.
int day = 4;
switch ( ) {
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
:
cout << "Weekend";
}
53
34. Print i as long as i is less than 6.
int i = 1;
(i < 6) {
cout << i << "\n";
;
}
int i = 1;
{
cout << i << "\n";
;
}
(i < 6);
(int i = 0; i < 5; ) {
cout << << "\n";
}
54
;
}
cout << i << "\n";
}
38. In the following loop, when the value is "4", jump directly to the next value.
Example 1 Convert the algorithm that asks the user for two integer values and compute and displays their
sum and product, into C++ codes.
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0, total = 0. product = 0;
cout << "Enter the first integer number: ";
cin>>x;
cout<<"Enter the first integer number: ";
cin>>y;
total = x+y;
product=x*y;
cout<<"The total of the two numbers are: "<<total<<"\n";
cout<<"The product of the two numbers are: "<<product<<"\n";
55
return 0;
}
Example 2. Convert the algorithm that will read in the width and length of a rectangular plot in
feet, and the price per square foot, the algorithm will compute and display the total price of the
plot, into C++ code.
Solution:
#include <iostream>
using namespace std;
int main()
{
int length = 0, width = 0, unit_price = 0. area = 0;, total_price = 0
cout << "Enter the Length : ";
cin>>length;
cout<<"Enter the Width : ";
cin>>width;
area = length*width;
total_price=area*unit_price;
cout<<"The total price is : "<<total_price<<"\n";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
double age = 0.0, pay_rate = 0.0, hours = 0.0, pay = 0.0;
cout << "Enter the age : ";
cin>>age;
cout<<"Enter the pay rate : ";
cin>>pay_rate;
cout<<"Enter the hours : ";
cin>>hours;
area = length*width;
total_price=area*unit_price;
if (age < 18.0)
{
pay = 2/3*pay_rate*hours;
56
}
else
{
pay = pay_rate*hours;
}
cout<<"The pay is : "<<pay<<"\n";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
double total = 0.0, score = 0.0;
int numb = 0, count = 0;
cout << "Enter the number of scores : ";
cin>>numb;
while (count < numb)
{
count += 1;
cout<<"Enter a score : ";
cin>>score;
total = total + score;
}
cout<<"The total score is : "<<total<<"\n";
}
#include <iostream>
using namespace std;
int main()
{
double minimum = 0.0, score = 0.0;
int numb = 0, count = 1;
cout << "Enter the number of scores : ";
cin>>numb;
cin>>score;
minimum = score;
while (count < numb)
{
count += 1;
57
cout<<"Enter a score : ";
cin>>score;
if (score < minimum)
{
minimum = score;
}
}
cout<<"The minimum of the scores is : "<<minimum<<"\n";
}
#include <iostream>
using namespace std;
int main()
{
double principal = 0.0, number = 0.0, rates = 0.0, interest = 0.0;
cout << "Enter the principal amount : ";
cin>>principal;
cout<<"Enter the number of years : ";
cin>>number;
cout<<"Enter the rates : ";
cin>>rates;
interest = (principal*number*rates)/100;
cout<<"The Simple Interest is : "<<interest;
}
#include <iostream>
using namespace std;
int main()
{
double X = 0.0, Y= 0.0, Z = 0.0, Big = 0.0;
cout << "Enter the first number : ";
cin>>X;
cout<<"Enter the second number : ";
cin>>Y;
cout<<"Enter the third number : ";
cin>>Z;
if (X > Y)
{
Big = X;
}
else
58
{
Big = Y;
}
if (Big < Z)
{
Big = Z;
}
cout<<"The Largest of the three numbers is : "<<Big;
}
#include <iostream>
using namespace std;
int main()
{
double maximum = 0.0, score = 0.0;
int numb = 0, count = 0;
cout << "Enter the number of scores : ";
cin>>numb;
cin>>score;
maximum = score;
while (count < numb)
{
count += 1;
cout<<"Enter a score : ";
cin>>score;
if (score > maximum)
{
maximum = score;
}
}
cout<<"The maximum of the scores is : "<<maximum<<"\n";
}
Example 11: Convert the algorithm in Example 11 of section 1, into C++ program.
#include <iostream>
using namespace std;
int main()
{
int prod = 1, I = 1, N = 0;
cout << "Enter the number of scores : ";
cin>>N;
59
while (I < N)
{
count += 1;
prod = prod * I;
}
cout<<"The factorial is : "<<prod<<"\n";
}
#include <iostream>
using namespace std;
int main()
{
double length = 1.0, width = 1.0, Area = 1.0, Perimeter = 1.0;
cout << "Enter the Length : ";
cin>>length;
cout << "Enter the Width : ";
cin>>width;
Area = Length*Width;
Perimeter = 2.0*(Length + Width);
cout<<"The Area is : "<<Area<<"\n";
cout<<"The Perimeter is : "<<Perimeter<<"\n";
}
3. Laboratory Exercises
Laboratory Session 1.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World ";
return 0;
}
1. Modify the program so that it requests your name, stores it in a string variable, and prints
out your name as stored in the string variable, as follows:
My name is
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.
60
2. Modify the program so that it requests for two integer numbers, stores them in integer
variables, a and b and displays the following results:
The values of a and b are:
a+b=
a -b=
a/b=
a%b=
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.
Laboratory Session 2.
#include <iostream>
using namespace std;
int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
for(int count = 1; count <=numb; count++)
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
}
cout << "The total is : " << total;
return 0;
}
0. Copy, compile and execute the program. Understand what the program does. It computes
n
the total of n scores, using this statistical formula, X
i =1
i
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.
1. Modify the program so that it computes the average of n scores, using this statistical
n
X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.
61
Scores 23 54 76 32 87
Average
2. Modify the program so that it computes the sum of squares of the scores, using this
n
X
2
statistical formula, i . Run the program using number as 5 and the various values of
i =1
scores as shown in the Table below. Write the result that the program will display in the
Table below. Make a screen print of the program, paste in a MS Word file, print it and
submit for assessment.
Scores 2 5 7 3 8
Sum of Square
3. Write an algorithm that will request for an integer, n, afterwards, it will request for n
different scores, Xi and compute computes and displays the sum of squares of the scores,
n
X
2
using this statistical formula, i .
i =1
4. Draw a flowchart that will represent the algorithm you have written in 3, above.
Laboratory Session 3.
#include <iostream>
using namespace std;
int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
int count = 0;
while (count < numb)
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
count += 1;
}
cout << "The total is : " << total;
62
return 0;
}
0. Copy and execute the program. Understand what the program does. It computes the total
n
of n scores, using this statistical formula, X
i =1
i
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.
1. Modify the program so that it computes the average of n scores, using this statistical
n
X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.
Scores 25 55 75 35 85
Average
2. Modify the program so that it computes the sum of squares of the scores, using this
n
X
2
statistical formula, i .Write the result that the program will display in the Table
i =1
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.
Scores 2 6 7 10 12
Sum of Square
3. Write an algorithm that will request for an integer, n, afterwards, it will request for n
different scores, Xi and compute computes and displays the sum of squares of the scores,
n
X
i =1
i
using this statistical formula, .
n
4. Draw a flowchart that will represent the algorithm you have written in 3, above.
Laboratory Session 4.
#include <iostream>
63
using namespace std;
int main() {
int numb = 0;
double score = 0.0;
double total = 0.0;
cout << "Enter the number of scores:";
cin >> numb;
int count = 0;
do
{
cout << "Enter a score : ";
cin >> score;
total = total + score;
count += 1;
}
while (count < numb);
cout << "The total is : " << total;
return 0;
}
0. Copy and execute the program. Understand what the program does. It computes the total
n
of n scores, using this statistical formula, X i =1
i
Make a screen print of the program, paste in a MS Word file, print it and submit for
assessment.
1. Modify the program so that it computes the average of n scores, using this statistical
n
X
i =1
i
formula, . Run the program using number as 5 and the various values of scores as
n
shown in the Table below. Write the result that the program will display in the Table
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.
Scores 25 55 75 35 85
Average
2. Modify the program so that it computes the sum of squares of the scores, using this
n
X
2
statistical formula, i .Write the result that the program will display in the Table
i =1
below. Make a screen print of the program, paste in a MS Word file, print it and submit
for assessment.
Scores 2 6 7 10 12
64
Sum of
Square
65