You are on page 1of 59

“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
➢ 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 3/20/2021 2


▪ 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 3/20/2021 3


if
▪ 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 3/20/2021 4


▪ 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 3/20/2021 5
▪ 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 3/20/2021 6


▪ 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 3/20/2021 7
➢ A one-way if statement performs an action if the
specified condition is true, but nothing is done if the
condition is false.

if-else
▪ 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 3/20/2021 8
▪ What is the output of the following code if number is 14,
15, and 30?

Computer Programming 3/20/2021 9


▪ What is the printout of the code in following if number is
30? What if number is 35?

Computer Programming 3/20/2021 10


if
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 3/20/2021 11


Computer Programming 3/20/2021 12
• 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 3/20/2021 13
Computer Programming 3/20/2021 14
Computer Programming 3/20/2021 15
▪ 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 3/20/2021 16


▪ 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 3/20/2021 17


▪ 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 3/20/2021 18


3/20/2021

The table below summarizes some typical situations


Computer Programming 19
switch

Computer Programming 3/20/2021 20


switch

Computer Programming 3/20/2021 21


switch

Computer Programming 3/20/2021 22


switch
• A switch statement executes statements based on the
value of a variable or an expression.

Computer Programming 3/20/2021 23


#include <iostream>
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 3/20/2021 24
• 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 3/20/2021 25


Computer Programming 3/20/2021 26
switch
#include <iostream>
OUTPUT:
using namespace std;
int main ( ) This is outer switch
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 3/20/2021 27
• 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 3/20/2021 28
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 3/20/2021 29
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 3/20/2021 30


▪ 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 3/20/2021 31


while
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 3/20/2021 32


▪ 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 3/20/2021 33


while
• Here is a “clever” observation about the digit
counting problem. Suppose a number n has d
digits. Then 𝑛/10 has 𝑑 − 1 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 3/20/2021 34


while
➢ 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 3/20/2021 35
while
➢ 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 3/20/2021 36
while 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 3/20/2021 37
do … while
• 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 3/20/2021 38



do … while
#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 3/20/2021 39
for
Previous statement;

for ( init; cond; inc /dec ) {


statement;
}

Next statement;

Computer Programming 3/20/2021 40


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 3/20/2021 41
Computer Programming 3/20/2021 42
▪ 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 3/20/2021 43


goto

Computer Programming 3/20/2021 44


• 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 3/20/2021 45


goto
// 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 3/20/2021 46


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 3/20/2021 47


goto
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 3/20/2021 48
break

• 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 3/20/2021 49


Computer Programming 3/20/2021 50
51
Computer Programming 3/20/2021
#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 )
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 3/20/2021 52
continue
• 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 3/20/2021 53


Computer Programming 3/20/2021 54
Computer Programming 3/20/2021 55
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
value of a: 19
}
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );

return 0;
}
Computer Programming 3/20/2021 56
break 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 3/20/2021 57


return
• 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 3/20/2021 58


▪ 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 3/20/2021 59

You might also like