You are on page 1of 28

Chapter Three

Flow Control Statements

05/03/22 1
Introduction
• The order in which statements are executed is called flow
control (or control flow).
• Flow control in a program is typically sequential, from one
statement to the next, but may be diverted to other paths by
branch statements.
• Flow control statements are used to divert the execution path
to another part of the program.
• Flow control statements:
– Conditional (Selection) statements: if, switch
– Loop statements: for, while, do-while
– Breaking control statements: break, continue, goto

05/03/22 2
Selection (Conditional) Statements
• Are mainly used for decision making.
• if Statement
– Varieties of if statement
• Simple if
• if … else
• if … else if … else
• Nested if
• Simple if
– Syntax:
if (expression) OR if (expression){
Statement; statment1;
statement2;
...
}

05/03/22 3
• Where
– expression is a statement that is evaluated to either true or false.
– Statement is a statement that will be executed if the expression
returns true. If expressions returns false nothing happens.
– For example,
• when dividing two values, we may want to check that the
denominator is nonzero:
if (count != 0)
average = sum / count;
• To make multiple statements dependent on the same condition,
we can use a compound statement:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
}
05/03/22 4
– if … else statement
• specify two alternative statements:
– one which is executed if a condition is satisfied and
– one which is executed if the condition is not satisfied.
• Syntax:
if (expression)
Statement1;
else
Statement2;
• For example:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
} else {
interest = balance * debitRate;
balance += interest;
}

05/03/22 5
• Write a program that will print the greatest of three numbers.
# include <iostream.h>
void main ()
{
int x, y, z, l;
cout << “Enter three numbers” <<“\n”;
cin >> x >> y>>z;
if (x > y )
l = x ;
else
l = y ;
if (l > z)
cout << “The greatest number is “ << l;
else
cout << “The greatest number is “<<z;
}

05/03/22 6
• The above example can be simplified to:
if (balance > 0)
interest = balance * creditRate;
else
interest = balance * debitRate;
balance += interest;
– if … else if … else Statement
• Syntax:
if (expression)
Statement1;
else if (expression)
Statement2;
else
Statement3;
• This type of if statement permits us to make a multi-way decision

05/03/22 7
• For example:
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special;

05/03/22 8
– Nested if statement
• If statements may be nested by having an if statement appear
inside another if statement.
• For example:
if (callHour > 6) {
if (callDuration <= 5)
charge = callDuration *
tarrif1;
else
charge = 5 * tarrif1 +
(callDuration - 5)
* tarrif2;
} else
charge = flatFee;

05/03/22 9
• Check If the input is Integer or not
#include <iostream>
#include <limits>
using namespace std;
int main() {
int age;
cout<<"Enter your age\n";
cin>>age;
if(cin.fail()){
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n’);
cout<<"wrong Input & Enter again\n";
cin>>age;
}
if(age == 18)
cout<<"Congratulations,you can vote\n";
else if(age < 18)
cout<<"Sorry, too young to vote\n";
else if(age > 60)
cout<<"Don't forget to vote\n";
else
cout<<"Get the vote out\n";
return 0;
}

05/03/22 10
• Switch Statement
– provides a way of choosing between a set of alternatives, based on
the value of an expression
– Syntax:
switch (identifier) {
case value1:
statements;
break;
...
case valuen:
statements;
break;
default:
statements;
}
05/03/22 11
– Execution continues until either
• a break statement is encountered or
• all intervening statements until the end of the switch statement are executed.
– The final default case is optional and is exercised if none of the earlier
cases provide a match
– For example:
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout<<"unknown operator: "<<operator;
}

05/03/22 12
– It should be obvious that any switch statement can also be
written as multiple if-else statements. But the reverse is not
always true.
– Switch statement is more readable than if statement
– Switch statement cannot check more than one variable at a
time.
– Switch statement works only for equality testing.

05/03/22 13
Looping (Iterative) Statements
• There are three looping statements in C++.
– while, do…while, and for
• The ‘while’ Statement
– provides a way of repeating a statement while a condition
holds.
– Syntax:
Initialization
While(condition) {
Statement;
Inc/Dec;
}
• This statement repeats executing the statement(s) until the
condition is false.
05/03/22 14
– For example:
int I = 0;
while (I < 10) {
Cout << I << “ “;
I ++;
}
– Output: 0 1 2 3 4 5 6 7 8 9

05/03/22 15
• The ‘for’ Statement
– is similar to the while statement, but has two additional
components:
• Expression which is evaluated only once before everything else
(initialization) and
• a Expression which is evaluated once at the end of each
iteration. (Condition and Inc/Dec)
– Syntax:
for (initialization; condition; Inc/Dec)
Statement;
– For example:
for (int I = 0; I < 10; I++)
Cout << I << “ “ ;
– Output: 0 1 2 3 4 5 6 7 8 9
05/03/22 16
– Any of the three expressions in a for loop may be empty
– For example, removing the first and the third expression gives
us something identical to a while loop:
for (; i != 0;) //is equivalent to:
something; //while(i!=0)
– Removing all the expressions gives us an infinite loop. This
loop's condition is assumed to be always true:
for (;;) // infinite loop
something;
– For loops with multiple loop variables are not unusual. In such
cases, the comma operator is used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;

05/03/22 17
• The ‘do…while’ Statement
– is similar to the while statement, except that its body is executed
first and then the loop condition is examined.
– Syntax:
Initialization
do {
Statement;
Inc/Dec;
}while(condition);
– In the case do … while statement, condition will be checked after
the statement is executed.
– It repeats the operation until the condition is false.
– The do loop is less frequently used than the while loop.
– It is useful for situations where we need the loop body to be
executed at least once, regardless of the loop condition.
05/03/22 18
– For example:
int I = 0;
do {
Cout << I << “ “;
I ++;
}while (I < 10);
– Output: 0 1 2 3 4 5 6 7 8 9
• Exercise: What is the output of the following three codes
int I = 10; int I = 10; for (int I=10;i<10;i++)
while(I < do { cout<<I ;
10) cout<< I; cout<< I;
{ I ++;
cout<< I; }while(I <
I ++; 10);
} cout<< I;
cout<< I;
05/03/22 19
• Nested Loop
– Because loops are statements, they can appear inside other
loops.
– For example:
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << ”(” << i << ”,” << j
<< ")\n";

05/03/22 20
Jumping Statements
• The ‘continue’ Statement
– terminates the current iteration of a loop and instead jumps to
the next iteration.
– It applies to the loop immediately enclosing the continue
statement.
– It is an error to use the continue statement outside a loop.
– In while and do loops, the next iteration commences from the
loop condition. In a for loop, the next iteration commences
from the loop’s third expression.

05/03/22 21
– For example, a loop which repeatedly reads in a number, processes it
but ignores negative numbers, and terminates when the number is
zero, may be expressed as:
do {
cin >> num;
if (num < 0)
continue;
// process num here...
} while (num != 0);
– This is equivalent to:
do {
cin >> num;
if (num >= 0) {
// process num here...
}
} while (num != 0);
05/03/22 22
– A variant of this loop which reads in a number exactly n times
(rather than until the number is zero) may be expressed as:
for (i = 0; i < n; ++i) {
cin >> num;
if (num < 0) continue;//causes a jump to:++i
// process num here...
}

05/03/22 23
– When the continue statement appears inside nested loops, it
applies to the loop immediately enclosing it, and not to the
outer loops.
– For example:
while (more) {
for (i = 0; i < n; ++i) {
cin >> num;
if (num < 0) // causes a jump
to: ++i continue;

// process num here...


}
//etc...
}

05/03/22 24
• 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.
– Like the continue statement, 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.

05/03/22 25
– For example, a loop which repeatedly reads in a number,
processes it but exit from the loop when encounters negative
number, otherwise, it works until the number is zero, may be
expressed as:
do {
cin >> num;
if (num < 0)
break;
// process num here...
} while (num != 0);

05/03/22 26
• The ‘goto’ Statement
– provides the lowest-level of jumping.
– Syntax:
goto label;
– where label is an identifier which marks the jump destination of goto.
– The label should be followed by a colon and appear before a
statement within the same function as the goto statement itself.
– For example:
do {
cin >> num;
if (num < 0)
goto out;
// process num here...
} while (num != 0);
out: //etc...

05/03/22 27
– Because goto provides a free and unstructured form of jumping
(unlike break and continue), it can be easily misused.
– Most programmers these days avoid using it altogether in favor
of clear programming.
– Nevertheless, goto does have some legitimate (though rare)
uses.

05/03/22 28

You might also like