MODULE 2
FLOW CONTROL (Part 1)
Learning Outcome:
At the end of this part of module 2, the students are expected to learn the following:
1. Understand the meaning of flow control in programming
2. How to use selection to reorder program flow
3. Types of select statements in C++
a. if statement
b. if…else statement
c. else…if statement
d. switch…case statement
e. Hands on examples
Definitions
You will already have found out that program execution starts from the top to the
bottom sequentially. This means that all codes must execute line by line starting from
the very first, then second, third and so on. But the interesting thing about
programming is to have those exhibits some kind of intelligence. This is only possible
if we are able to allow the execution of code decide when to alter the sequential
execution. Flow control will allow the program execution to make choice of what
section of the codes to execute at one point or another. There are two types of Flow
Control, Selection and Looping (Iteration).
2.1 Selection
This type of flow control enable program to change their execution behavior when
certain conditions are met. This means that selection uses certain conditionals to test
the value of input parameters. If the test condition is met, certain sequence of program
structure will be executed. If the condition fails, another sequence of program
structure will be expected to execute. In other words, selection control structure is
used to decide which sequence of codes executes or not depending on the result of
the condition after evaluation.
2.1.1 Conditions
Conditions are used to allow the program to check (test) the values of variables and
to execute (or not execute) certain statements. Conditions will always evaluate to be
True or False. Conditions can be setup using any of Boolean expression, logical
operators and comparison operators or a combination of any of these.
2.1.1.1 Comparison Operators
When we want to determine whether a condition is true or false, we use the
comparison operators. There are six of such operators as shown in table 1.1.
Table 1.1: Comparison Operators
Operator Meaning
> Greater than
< Less than
>= Greater or equals
<= Less or equals
!= Not equals
== Equals
If we have two variables, say x and y, where x = 2 and y = 6, then we can say that x >
y is false, x != y is true, and so on.
2.1.1.2 Logical Operators
Logical operators are used when we want to combine two or more comparison
operators in a single conditional expression. Again, the result of such combination
evaluates to be either true or false. See table 2.2.
Table 2.2: Logical Operators
Logical Operator Meaning Example Description
&& And x && y Evaluates to true if and only if x and
y are true
|| Or X || y Evaluates to true if at least x or y is
true
! Not !x Evaluates to true if and only if x is
false
We will use the following truth table to illustrate further:
x y x && y x y x || y
False False False False False False
False True False False True True
True False False True False True
True True True True True True
x !x
False True
True False
Consider the following conditions and resulting outputs if x = 2 and y = 6:
!(x > 2) → true
(x > y) && (y > 0) → false
(x < y) && (y > 0) → true
(x < y) || (y > 0) → false
2.1.1.3 Boolean Expression
A boolean expression is a condition that is either true or false. For example the
expressions d > 0, n%d == 0, and (d > 0 && n%d == 0) are boolean expressions. As
we have seen, boolean expressions evaluate to integer values. The value 0 means
“false” and every nonzero value means “true.”
Since all nonzero integer values are interpreted as meaning “true,” boolean
expressions are often disguised.
2.1.2 if, if…else and else if Statements
if (condition) statement;
where condition is an integral expression and statement is any executable statement.
The statement will be executed only if the value of the integral expression is nonzero,
that is if the condition is true.
This syntax is used when only one statement is involved. If multiple statements are
involved, the following syntax applies:
if(condition)
{
statement1
statement2
…
}
Program 2.1: if with Single Statement Block
1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int n,d;
6 cout << "Enter two positive integers: ";
7 cin >> n >> d;
8 if (n%d) cout<<n<<" is not divisible by "<< d << endl;
9 }
In line 8, we have a single if statement block. The condition (n%d) evaluates the
remainder after integer division. If the remainder greater than zero, the the only
stamen block cout << n << " is not divisible by " << d << endl; will
be executed.
Program 2.2: if with multiple Statement blocks
1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int n,d;
6 cout << "Enter two positive integers: ";
7 cin >> n >> d;
8 if (n%d)
9 {
10 cout<<”This statement 1 executing”<<endl;
11 cout<< n << " is not divisible by " << d << endl;
12 cout<<”We can have more statements here”<<end;
13 }
13 }
The difference we can see in program 2.1 and 2.2 is from line 9 to 13 in program 2.2.
Once there are more than one line of statements to be executed when the condition
evaluates to be true, we must enclose those statements in braces as shown.
if…else Statement
The if statement we have used so far does not do anything if the condition evaluates
to false. In the if…else, we will allow some statement (s) to execute whenever the
condition is not true.
Syntax:
if(condition)
{
statementA1
statementA2
…
}
else
{
statementB1
statementB2
…
}
The braces can be omitted if there is just one statement to be executed in the if or else
blocks.
Program 2.3: if…else Statement with single statement block
1 #include <iostream>
2 using namespace std;
3 int main() {
4 int x = 6;
5 int y = 2;
6 if(x > y)
7 cout << “x is greater than y\n”;
8 else if(y > x)
9 cout << “y is greater than x\n”;
10 else
11 cout << “x and y are equal\n”;
12 return 0;
16 }
else…if Statement
When we have a set of parallel alternatives, else…if construct is used to provide those
alternative options during execution.
Syntax:
if(condition1)
{
statementA1
statementA2
…
}
else if(condition2)
{
statementB1
statementB2
…
}
.
.
.
else
{
statementB1
statementB2
…
}
Program 2.4: Determining the Grades of entered Score
1 #include <iostream>
2 using namespace std;
3 int main() {
4 int score
5 char grade;
6 cout<<”Enter a score”;
7 cin>>score
8 if(score<40)
9 cout << “Grade = F\n”;
10 else if(score<=44)
11 cout << “Grade = E\n”;
12 else if (score<=49)
13 cout << “Grade = D\n”;
14 else if (score<=59)
15 cout<<”Grade =C\n”;
16 else if (score<=69)
17 cout<<”Grade =B\n”;
18 else if (score<=100)
19 cout<<”Grade =A\n”;
20 return 0;
21 }
2.1.3 switch…case Statement
The switch statement can be used instead of the else if construct to implement a
sequence of parallel alternatives.
Syntax:
switch (expression)
{
case constant1: statementList1;
case constant2: statementList2;
case constant3: statementList3;
: :
case constantN: statementListN;
default: statementList0;
}
This evaluates the expression and then looks for its value among the case
constants. If the value is found among the constants listed, then the statements in the
corresponding statementList are executed. Otherwise if there is a default (which
is optional), then the program branches to its statementList. The expression
must evaluate to an integral type and the constants must be integral constants.
Program 2.5: Computing Grade using switch…case
1 #include <iostream>
2 using namespace std;
3 int main() {
4 int score
5 char grade;
6 cout<<”Enter the Score”<<endl;
7 cin>>score;
8 switch(score/10)
9 { case 1:
10 case 2:
11 case 3:
12 cout<<”Grade = F”<<endl; break;
13 case 4:
14 cout<<”Grade = D”<<endl; break;
15 case 5:
16 cout<<”Grade = C”<<endl; break;
17 case 6:
18 cout<<”Grade = B”<<endl; break;
19 case 7:
20 case 8:
21 case 9:
22 case 10:
23 cout<<”Grade = A”<<endl; break;
24 default:
25 cout<<”You entered a wrong score”<<endl;
26 }
27 }
Notice the use of break keyword at the end of each case set. It is used to tell the
compiler that a particular statement block has ended. Using cascaded case enables
you to select a range of values.
Problem Set
3 Looping (Iteration)
Looping or iteration is a program construct that is used to cause the execution of
certain statement blocks to be repeated over a desired number of times while a set
condition remains true. This implies that a condition is required to set up a loop
construct or structure. In C++, there are three statements used for loop construct.
These are:
1. for statement
2. do…while Statement
3. while Statement
3.1 The while Statement
In this construct, the statement blocks will continue to execute if and only if the
condition is true and remains true.
Syntax:
while (condition)
{
Statement 1
Statement 2
:
:
}
Where condition is the expression that must evaluate to zero (false) or non-zero (true).
Statement blocks within the while loop will continue to execute as long as the condition
expression evaluates to be non-zero or true.
Program 3.1: Program to count all integers from 0 to 9
1 #include <iostream>
2 using namespace std;
3 int main() {
4 int x = 0;
5 while(x < 10)
6 x = x + 1;
7 cout << “x is “ << x << “\n”;
8 return 0;
9 }
There are a total of 10 integers from 0 to 9. Therefore the output of the program is 10.
3.2 The do … while Statement
This construct resembles the former, but unlike the former, the statements will execute at
least once since the loop comes before the condition.
Syntax:
do
{
Statement 1
Statement 2
:
:
}
While (condition);
Program 3.2: Program to display all integers from 1 to 50
1 #include <iostream>
2 using namespace std;
3 int main() {
4 int x = 1;
5 do
6 {
7 cout << “x is “ << x << “\n”;
8 x++;
9 }
10 while(x <= 50);
11 return 0;
12 }
Note: you must open and close braces for the statement blocks in the do segment and the
while component must be terminated with semi colon as shown in program 3.2.
3.3 The for Statement
Another statement used in the loop construct is the for loop statement. The syntax is as
shown below:
Syntax
for (initialize-counter; condition; increment-counter)
{
Statement 1
Statement 2
:
:
}
Where
initialize-counter is an expression that is used to declare and initialize a control
variable,
condition is the expression that must be evaluated to determine if the statement block will
continue to execute or not and
increment-counter is used to increment or decrement count of the control variable until
the condition becomes false.
Program 3.3: Program to compute the sum of all integers from 1 to 100
1 #include <iostream>
x sum output
2 using namespace std;
1 0 1
3 int main() { 2 1 3
3 3 6
4 sum = 0; 4 6 10
5 for(x = 1; x <= 100; x++)
6 {
7 sum = sum + x;
8 }
9 cout << “Sum is “ << sum << “\n”;
10 return 0;
11 }
Notice in Line 5, for(x = 1; x <= 100; x++), that there are three statements depicting
what the syntax says. x = 1 initializes the counter to 1, x++ is used for accumulating the
counter, and x <= 100 (meaning until x is less or equals 100) specifies the range of the count.
The execution of the loop will stop once the counter value goes out of the range. Since the
initial value of x is 1 and the last value is 100, the range of count is 1 to 100. Hence program
3.3 will display the sum of all the number between 1 and 100.
3.4 Nested Flow Control
When a control flow construct is cascaded, it is known as nested flow control. This is
used when we want to solve computational problems that is more intricate.
3.4.1 Nested Selection
Program 3.4: Program involving nested if
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x = 6;
6 int y = 0;
7
8 if(x > y) {
9 cout << “x is greater than y\n”;
10 if(x == 6)
11 cout << “x is equal to 6\n”;
12 else
13 cout << “x is not equal to 6\n”;
14 } else
15 cout << “x is not greater than y\n”;
16
17 return 0;
18 }
3.4.2 Nested Loop
Program 3.5: Program to compute the multiplication table
1 #include <iomanip> // defines setw()
2 #include <iostream> // defines cout
3 using namespace std;
4 int main()
5 {
6 for (int x=1; x <= 12; x++)
7 {
8 for (int y=1; y <= 12; y++)
9 cout << setw(4) << x*y;
10 cout << endl;
11 }
12 }
Problem Sets:
1. Compute Fibonacci Series
2. Compute the sum of reciprocals
3. Compute the sum of all integers in a range
4. Compute the factorial of a given integer number
5. Develop a multiplication table for any number
Practical
00