You are on page 1of 59

Flow of Control

“Would you tell me, please, which way I ought to go from here?”
“That depends a good deal on where you want to get to,” said the Cat.
̶ LEWIS CARROLL , Alice in Wonderland

CHAPTER 3
Control of Flow
 A flow control statement can cause a change in the
subsequent controls of flow to differ from the natural
sequential order in which the instructions are listed.
 Flow control roughly categorized into 3. These are:

1. Conditional/Branching/selection statements
2. Iteration/Looping/Repetition statements
3. Jumping statements

Computer Programming 12/20/2022 2


1. Conditional or Selection
Statements

 The program can decide which statements to execute


based on a condition.

 C++ provides several types of selection statements:


1. one-way if statements,
2. two-way if-else statements,
3. nested if and multi-way if-else statements,
4. switch statements, and
5. conditional expressions.

Computer Programming 12/20/2022 3


1.1. The One-way if statement
 The syntax for a one-way if statement is shown here:
Flowchart

if (Boolean_expression)
{
statement(s);
}

 It executes an action if and only if the condition is true.

Computer Programming 12/20/2022 4


Continued

 If the boolean-expression evaluates to true, the


statements in the block are executed.
E.g., if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
}
 The braces can be omitted if they enclose a single
statement. E.g., if (i > 0)
cout << "i is positive" << endl;
Computer Programming 12/20/2022 5
Class Work
 Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, display Hello Five. Also, if the number
is even, display Hello Even.
Ans. #include <iostream>
using namespace std;
int main() { int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 5 == 0) cout << "Hello Five!" << endl;
if (number % 2 == 0) cout << "Hello Even!" << endl;
return 0;
}

Computer Programming 12/20/2022 6


Class Work
 What is wrong in the following code?
Logic Error
if (radius >= 0);
{
area = radius * radius * PI;
cout << "The area " << " is " << area;
}
 This mistake is hard to find, because it is neither a
compile error nor a runtime error; it is a logic error.

if (radius >= 0); if (radius >= 0) { };


Empty Body
Computer Programming 12/20/2022 7
 A one-way if statement performs an action if the
specified condition is true, but nothing is done if the
condition is false.

1.2. Two-way if-else statement


 An if-else statement decides which statements to execute
based on if the condition is true or false.

if (Boolean_expression) Flowchart
{
Syntax

statement(s)-of-true-case;
}
else
{
statement(s)-of-false-case;
}
Computer Programming 12/20/2022 8
Class Work
 What is the output of the following code if number is 14,

15, and 30?

Computer Programming 12/20/2022 9


Class Work
 What is the printout of the code in following if number is
30? What if number is 35?

Computer Programming 12/20/2022 10


1.3.1 Nested if Statement
An if statement can be inside another if
statement to form a nested if statement.
Syntax

if (i > k)
{
if (j > k)
cout << "i and j are greater than k" << endl;
}
else
cout << "i is less than or equal to k" << endl;

The if (j > k) statement is nested inside the if (i > k).


The nested if statement can be used to implement multiple
alternatives.
Computer Programming 12/20/2022 11
Nested if flowchart

Computer Programming 12/20/2022 12


1.3.2 The Multi-Way if-else Statement

• A preferred format for multiple alternatives is shown in (b) using


a multi-way if-else statement
• This style, called multi-way if-else statements, avoids deep
indentation and makes the program easy to read.
Computer Programming 12/20/2022 13
Multi-Way if-else flowchart

Computer Programming 12/20/2022 14


Multi-way if-esle flowchart
to assign grade.

Computer Programming 12/20/2022 15


Class Work
 What is wrong in the following code?

if (score >= 60.0)


cout << "Grade is D";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 90.0)
cout << "Grade is A";
else
cout << "Grade is F";
Computer Programming 12/20/2022 16
Home Work
 Suppose x = 3 and y = 2; show the output, if any, of the
following code. What is the output if x = 3 and y = 4? What
is the output if x = 2 and y = 2?
 Draw a flowchart of the code.

if (x > 2) {
if (y > 2) {
int z = x + y;
cout << "z is " << z << endl;
}
}
else
cout << "x is " << x << endl;
Computer Programming 12/20/2022 17
Home Work
 Suppose x = 2 and y = 3. Show the output, if any, of the
following code. What is the output if x = 3 and y = 2?
What is the output if x = 3 and y = 3?

if (x > 2)
if (y > 2)
{
int z = x + y;
cout << "z is " << z << endl;
}
else
cout << "x is " << x << endl;

Computer Programming 12/20/2022 18


12/20/2022

The table below summarizes some typical situations


Computer Programming 19
1.4. The switch Statement

Computer Programming 12/20/2022 20


The switch Statement
Syntax:

Computer Programming 12/20/2022 21


The switch Statement flowchart

Computer Programming 12/20/2022 22


E.g. Simple Calc. using switch
• A switch statement executes statements based on the
value of a variable or an expression.

Computer Programming 12/20/2022 23


#include <iostream>
continued
using namespace std;  Commenting Grades using switch
int main () { statement.
char grade = ‘B’;
switch(grade) {
case ‘A’ : cout << “Excellent!” << endl;
break;
case ‘B’ :
case ‘C’ : cout << “V. Good!” << endl;
break;
case ‘D’ : cout << “Poor!” << endl;
break;
case ‘F’ : cout << “Fail!” << endl;
break;
default : cout << “Invalid grade” << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
V. Good!
}
Computer Programming Your grade is B 12/20/2022 24
continued
• Here is an example which has fall-throughs. Suppose we
want to print the number of days in the nth month of the
year, taking n as the input. Here is the program.

Computer Programming 12/20/2022 25


continued

Computer Programming 12/20/2022 26


Nested switch Statement
#include <iostream>
OUTPUT:
using namespace std;
This is outer switch
int main ( )
This is inner switch
{ The value of a is : 100
int a = 100; The value of b is : 200
int b = 200;
switch (a) {
case 100: cout << "This is outer switch" << endl;
switch (b) {
case 200: cout << "This is inner switch" << endl;
}
}
cout << "The value of a is : " << a << endl;
cout << "The value of b is : " << b << endl;

return 0;
}
Computer Programming 12/20/2022 27
1.5. The Conditional Expressions
• A conditional expression evaluates an expression based on
a condition.
Syntax: boolean-expression ? expression1 : expression2;
• For example, the following statement assigns 1 to y if x is
greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0) y = x > 0 ? 1 : -1;


y = 1;
else
 You might want to assign a variable
y = -1;
a value that is restricted by certain
conditions.
E.g. int max = (a>b) ? a : b;
Computer Programming 12/20/2022 28
1.5.1 Nested ternary operators
Conditional expressions an be nested, i.e. the consequent or
alternate expressions an themselves conditional expressions.
This allows us to write tax calculation program.

No. Salary Range (ETB) Tax Rate Deduction (ETB)

1. 0 – 600 Birr Non-Taxable –


2. 601 – 1,650 Birr 10% 60 Birr
3. 1,651 – 3,200 Birr 15% 142.50 Birr

4. 3,201 – 5,250 Birr 20% 302.50 Birr

5. 5,251 – 7,800 Birr 25% 565 Birr

6. 7,801 – 10,900 Birr 30% 955 Birr

7. Over 10,900 Birr 35% 1,500 Birr

Computer Programming 12/20/2022 29


continued
Sample Calculation: If the salary of an employee is 2,000 Birr.
By referring to the above table, we can see that 2,000 birr falls in the No. 4
row. So, Tax Rate = 15% and deduction = 142.50
Income Tax = (2,000 Birr x 15%) – 142.50 Birr = 157.50 Birr

float income;
cin >> income;
float incomeTax = income <= 600 ? 0 :
income <= 1650 ? (income * 0.1) - 60 :
income <= 3200 ? (income * 0.15) - 142.5 :
income <= 5250 ? (income * 0.2) - 302.5 :
income <= 7800 ? (income * 0.25) - 565 :
income <= 10900 ? (income * 0.3) - 955 :
(income * 0.35) - 1500 ;

Computer Programming 12/20/2022 30


3. Iteration or Looping Statements
 it is required to repeatedly evaluate a statement or a
whole block of statements with increment/decrement
of some data in order to arrive at a result.
 Repeated evaluation of statements is called iteration
and recursion. However, iteration is about looping.
 C++ provides several
1. while statements,
types of iteration
2. do … while statements,
statements:
3. for statements, and
4. goto statements.

Computer Programming 12/20/2022 31


2.1. The while loop
Syntax: while (conditional expression)
statements;
 This implies the statement following it will be carried out
as long as the conditional expression evaluates true, i.e.
it is more than zero.
E.g. let variables n, i and Sum are declared as integers.
The number n is initialized as 10, Sum as 0 and i as 0.
while (i <= n)
Sum += i++;
cout << “Sum 0 to 10 = ” << Sum <<endl;
 The process is repeated again and again till i =10. So Sum
will become 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
 After the loop is over, Sum 0 to 10 = 55 will be printed.

Computer Programming 12/20/2022 32


Class Work
 Now, you need to determine the square roots of numbers 0,
10, 20, 30, and 40. and display them.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int n=10, N, i=0;
while(i<5){
N = i*n;
cout <<“Number = “ << N <<“\tSquare
root = “<< sqrt(N) <<endl;
i++;
}
return 0;
}

Computer Programming 12/20/2022 33


while loop Exercise
• Here is a “clever” observation about the digit
counting problem. Suppose a number n has d
digits. Then has digits. Thus we simply count the
number of times we can divide by 10 till we get zero
and that will be the number of digits of the number.
So the program is:

Computer Programming 12/20/2022 34


2.1.1 Nested while loops – Home Work
 The following program illustrates the nested while loops.
What is the printout of the code?
 void main(){
int x=0, i=0;
cout<< “i\tj\tx\ty” <<endl;
while (i<=2){
int j = 0; // outer while loop
while (j<=2){
x+=(i+j); // inner while loop
int y = x*x;
cout<< i <<‘\t’<< j <<‘\t’<< x <<‘\t’<< y <<endl;
j=j+1;
}
i =i+1;
}}
Computer Programming 12/20/2022 35
2.1.2 compound while condition – H.W.
 What is the printout of the following code?
#include <iostream>
using namespace std;
int main(){
int x=0, i=2, j=0, k=0, y;
cout<<“i\tj\tk\tx\ty” <<endl;
while(i>=2,i<=4,j<=5,k<=6){ //comp’d while cond’n
x =(i+j+k);
y = x*x;
cout<<i<<‘\t’<<j<<‘\t’<<k<<‘\t’<<x<<‘\t’<<y<<‘\n’;
j++;
i++;
k++;
}
return 0;
}
Computer Programming 12/20/2022 36
2.1.3 while loop with compound Boolean expression H.W.
 What is the printout of the following code?
#include <iostream>
using namespace std;
int main(){
int x=0, i=3, j=0, y;
cout<<“i\tj\tk\tx\ty” <<endl;
while(j<5 && i>=3 && i<=10)
{ //compound while Boolean expression
x += (i+j);
y = x*x;
cout<< i <<‘\t’<< j <<‘\t’<< x <<‘\t’<< y <<endl;
j++;
i++;
}
return 0;
}
Computer Programming 12/20/2022 37
2.2. The do … while Statement
• The use of do…while loop is similar to while loop
except for the fact that the while condition is
evaluated at the end of program.
• So, at least one computation would be carried out
even if the while condition turns out false in the
execution of do … while loop. (see the flowchart below)

Computer Programming 12/20/2022 38


2.2.1 Factorial of numbers with
do … while loops – Class Work

#include <iostream>
using namespace std;
int main(){
int x=0, i=0, factorial = 1, limit = 500;
cout<<“i”<<“\tx”<<“\t” << “Factorial x” <<endl;
do{
i = i + 1;
x += 1;
factorial *= x;
cout<< i <<“\t”<< x <<“\t”<< factorial <<endl;
} while ( factorial < limit );

return 0;
}
Computer Programming 12/20/2022 39
2.3. The for loop
Previous statement;

for ( init; cond; inc /dec ) {


statement;
}

Next statement;

Computer Programming 12/20/2022 40


Time to Exercise

What is the value of m and n after executing


the following code?
int n = 123456789;
int m = 0;
while (n != 0) {
m = (10 * m) + (n % 10);
n = n / 10;
}
What does the following code print out?
int f = 0, g = 1;
for (int i = 0; i <= 15; i++) {
cout << f;
f = f + g;
g = f - g;
}
Computer Programming 12/20/2022 41
Summary:

Computer Programming 12/20/2022 42


3. Jumping Statements
 Loop control statements or jumping statements
change execution from its normal sequence.
 When execution leaves a scope, all automatic objects
that were created in that scope are destroyed.
 C++ supports the following jumping statements:
1. goto statements,
2. break statements,
3. continue statements, and
4. return statements

Computer Programming 12/20/2022 43


3.1. The goto statement

Computer Programming 12/20/2022 44


continued

• The code goto is used for moving back and forth in the
program. Therefore, for using goto statement one
needs to put in a label.
• Syntax:

Computer Programming 12/20/2022 45


Example 1: goto Statement
// This program calculates the average of numbers entered by user.
// If user enters negative number, it ignores the number and
// calculates the average of number entered before it.

# include <iostream>
using namespace std;
int main( )
{
float num, average, sum = 0.0;
int i, n;

cout << "Maximum number of inputs: ";


cin >> n;

Computer Programming 12/20/2022 46


continued
for (i = 1; i <= n; ++i)
{
cout << "Enter n" << i << ": ";
cin >> num;

if (num < 0.0)


{
// Control of the program move to jump, which is label.
goto jump;
}
sum += num;
}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}

Computer Programming 12/20/2022 47


Example 2: goto Statement as a looping
int main(){
int n , m;
cout<<“Write and enter two integers: ” ;
cin>> n >> m;
cout<< “You have written the numbers as n= ”<<n <<“
and m = ”<<m <<endl;
Again: //The label Again, see colon at end.
if(n < m) n++; else m++;
if(n == m)
cout<<“Now m = ” << m<<“ and n = ” << n<<“\n”;
else
goto Again; //Jump back to Again making a loop
return 0;
}
Computer Programming 12/20/2022 48
3.2. The break statement

• A break statement may appear inside a loop (while,


do, or for) or a switch statement.
• It causes a jump out of these constructs, and hence
terminates them.
• A break statement only applies to the loop or switch
immediately enclosing it.
• It is an error to use the break statement outside a
loop or a switch.

Computer Programming 12/20/2022 49


continued

Computer Programming 12/20/2022 50


E.g. C++ program to add all number entered until the user enters 0.

51
Computer Programming 12/20/2022
Exercise: Show the output
#include <iostream>
using namespace std;
int main(){
int a = 10; // Local variable declaration

do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15 ) break;
value of a: 10
} while( a < 20 ); value of a: 11
value of a: 12
return 0; value of a: 13
value of a: 14
}
value of a: 15
Computer Programming 12/20/2022 52
3.3. The continue statement
• continue statement causes the loop to skip the rest of
its body and immediately retest its condition prior to
reiterating.
• For the for loop, continue causes the conditional test
and increment portions of the loop to execute.
• For the while and do...while loops, program control
passes to the conditional tests.
• It is an error to use the continue statement outside a
loop.

Computer Programming 12/20/2022 53


continued

Computer Programming 12/20/2022 54


E.g. C++ program to display integer from 1 to 10 except 6 and 9.

Computer Programming 12/20/2022 55


Example: Show the output
int main () { value of a: 10
value of a: 11
int a = 10; // Local variable value of a: 12
do { value of a: 13
value of a: 14
if( a == 15 ) { value of a: 16
a = a + 1; value of a: 17
value of a: 18
continue; value of a: 19
}
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );

return 0;
}
Computer Programming 12/20/2022 56
break vs. continue
The continue statement works somewhat like the break
statement. Instead of forcing termination, however, continue
forces the next iteration of the loop to take place, skipping
any code in between.

Computer Programming 12/20/2022 57


3.4. The return statement
• The return statement enables a function to return a
value to its caller. It has the general form:
return expression;
• where expression denotes the value returned by the
function. The type of this value should match the
return type of the function.
• For a function whose return type is void, expression
should be empty:
return;

Computer Programming 12/20/2022 58


continued

 The only function we have discussed so far is main,


whose return type is always int.
 The return value of main is what the program returns
to the operating system when it completes its
execution.
 For example, its conventional to return 0 from main
when the program executes without errors.
Otherwise, a non-zero error code is returned.

Computer Programming 12/20/2022 59

You might also like