Chapter 3
Chapter 3
Chapter Three
Control Statements
Flow control in a program is typically sequential, from one statement to the next, but may be
diverted to other paths by branch statements. There are 3 types of flow control statements: i)
Conditional Statements, ii) Loop Statements and iii) Branching Statements.
-1-
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 3
First, expression is evaluated. If the outcome is nonzero (true), then statement1 is executed;
otherwise, statement2 is executed.
For example
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
} else {
interest = balance * debitRate;
balance += interest;
}
Given the similarity between the two alternative parts, the whole statement can be simplified to:
if (balance > 0)
interest = balance * creditRate;
else
interest = balance * debitRate;
balance += interest;
-2-
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 3
following the matching case are then executed. 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: " << ch << '\n';
break;
}
-3-
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 3
i++;
}
Let n set to 5. Then, we can show a trace of the loop by listing the values of the variables involved
and the loop condition as follows:
Iteration i n i <= n sum += i++
First 1 5 1 1
Second 2 5 1 3
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0
-4-
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 3
-5-
WUGC, CNCS, Computer Programming (Comp1033) for LAM-I, Sem. II, 2017 Chapter 3
-6-