Chapter three
Control Statements
outline
• Introduction
• CONDITIONAL STATEMENTS
• if Statement
• switch Statement
• LOOPING STATEMENTS
• ‘for’ Statement
• ‘while’ Statement
• ‘do…while’ Statement
• OTHER STATEMENTS
• ‘continue’ Statement
• ‘break’ Statement
• ‘goto’ Statement
• ‘return’ Statement
Introduction
• When a program runs, it executes statements in a specific order.
• This is known as flow control (or control flow).
• The term reflects how control of the CPU moves from one statement to the next during
execution.
• By default, flow control is sequential, meaning the program executes statements one after
another.
• However, it can branch, change direction based on certain conditions, allowing different
paths of execution.
• This behavior is crucial, as it determines which parts of the code are run and which are
skipped, ultimately affecting the program’s outcome.
• C++, like in many procedural languages, there are various types of statements for managing
flow control.
Introduction(cont…)
• declaration Statements: Define variables and their types.
• Assignment Statements: Perform calculations and assign values.
• Branching Statements: Direct the program to different paths based on conditions.
• e.g., if, else, switch.
• loop Statements: Repeat a block of code until a condition is met.
• e.g., for, while, do-while.
• Jump/Flow Control Statements: Transfer control explicitly
• e.g., break, continue, goto, return.
• Each type of statement plays a role in shaping the logic and behavior of
a program.
• Understanding flow control is key to writing efficient, logical, and
functional code.
Conditional Statements
1. The if Statement
• It is sometimes desirable to make the execution of a statement dependent upon a
condition being satisfied.
• The if statement provides a way of expressing this, the general form of which is:
if (expression)
statement;
• First expression is evaluated.
• If the outcome is nonzero (true) then statement is executed.
• Otherwise, nothing happens.
The if Statement(cont…)
• 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;
}
The if Statement(cont…)
• A variant form of the if statement allows us to specify two alternative statements:
• one which is executed if a condition is satisfied and one which is executed if the
condition is not satisfied.
• This is called the if-else statement and has the general form:
if (expression)
statement1;
else statement2;
• First expression is evaluated and If the outcome is nonzero (true) then statement1
is executed. Otherwise, statement2 is executed.
The if Statement(cont…)
• E.g: the similarity between the two alternative parts.
if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
else {
interest = balance * debitRate;
balance += interest;
}
The if Statement(cont…)
• Or simplified even further using a conditional expression:
interest = balance * (balance > 0 ? creditRate : debitRate);
balance += interest;
Or just:
balance += balance * (balance > 0 ? creditRate : debitRate);
The 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;
The nested if Statement(cont….)
• A frequently-used form of nested if statements involves the else part consisting of
another if-else statement.
• For example:
if (ch >= '0' && ch <= '9')
kind = digit;
else {
if (ch >= 'A' && ch <= 'Z')
kind = upperLetter;
else {
if (ch >= 'a' && ch <= 'z')
kind = lowerLetter;
else
2. The switch Statement
• The switch statement provides a way of choosing between a set
of alternatives, based on the value of an expression.
• The general form of the switch statement is:
switch (expression) {
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}
The switch Statement(cont…)
• First expression (called the switch tag) is evaluated, and the outcome is
compared to each of the numeric constants (called case labels), in the order
they appear, until a match is found.
• The statements following the matching case are then executed.
• Note the plural: each case may be followed by zero or more statements (not
just one statement).
• 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.
The switch Statement(cont…)
• For example, suppose we have parsed a binary arithmetic operation into its
three components and stored these in variables operator, operand1, and
operand2.
• The following switch statement performs the operation and stores the result
in result.
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;
}
The switch Statement(cont…)
• It should be obvious that any switch statement can also be written as multiple if-else
statements.
• The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
Looping Statements
1. The ‘while’ Statement
• The while statement (also called while loop) provides a way of repeating a
statement while a condition holds.
• The general form of the while statement is:
while (expression)
statement;
The ‘while’ Statement
• First expression (called the loop condition) is evaluated.
• If the outcome is nonzero then statement (called the loop body) is
executed and the whole process is repeated.
• Otherwise, the loop is terminated.
• For example, suppose we wish to calculate the sum of all numbers from
1 to some integer denoted by n. This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
sum += i;
The ‘while’ Statement(cont..)
• For n set to 5, on the table below provides a trace of the loop by listing
the values of the variables involved and the loop condition.
2. The ‘for’ Statement
• The for statement (also called for loop) is similar to the while statement.
• But has two additional components:
• An expression which is evaluated only once before everything else,
• And an expression which is evaluated once at the end of each iteration.
• The general form of the for statement is:
for (expression1; expression2; expression3)
statement;
• First expression1 is evaluated, Each time round the loop, expression2 is evaluated.
• If the outcome is nonzero then statement is executed and expression3 is evaluated.
The ‘for’ Statement(cont…)
• The general for loop is equivalent to the following while loop:
expression1;
while (expression2) {
statement;
expression3;
}
The ‘for’ Statement(cont…)
• The most common use of for loops is for situations where a variable is
incremented or decremented with every iteration of the loop.
• for example, calculates the sum of all integers from 1 to n.
Int sum = 0;
Int i = 0;
for (i = 1; i <= n; ++i)
sum += i;
• In this example, i is usually called the loop variable.
Nested For loops
• loops can be nested.
• For example,
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";
3. The ‘do…while’ Statement
• The do statement (also called do loop) is similar to the while statement, except that
its body is executed first and then the loop condition is examined.
• The general form of the do statement is:
do
statement;
while (expression);
• First statement is executed and then expression is evaluated.
• If the outcome of the latter is nonzero then the whole process is repeated, Otherwise,
the loop is terminated.
• 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.
The ‘do…while’ Statement(cont…)
• For example, suppose we wish to repeatedly read a value and print its square, and
stop when the value is zero.
• This can be expressed as the following loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
Other Statements
1. The ‘continue statement
• It's used inside loops to skip the rest of the current iteration and move to the next
iteration of the loop.
• When the program hits a continue;, it ignores everything below it inside the loop
body and goes back to the loop condition check (or the update statement in a for
loop).
for (int i = 1; i <= 5; i++) { output
if (i == 3) {
continue; // Skip when i is 3
}
cout << "i = " << i << endl;
}
2. The ‘break’ Statement
• ‘Break’ Statement is used to immediately exit a loop or a switch statement.
• When the program hits a break, it jumps out of the loop or switch, skipping any
remaining code inside it.
for (int i = 1; i <= 5; i++) { output
if (i == 3) {
break; // Exit loop when i is 3
}
cout << "i = " << i << endl;
}
return 0;
}
3. The ‘goto’ Statement
• The goto statement is used to jump unconditionally to another part of the program,
specified by a label or it provides the lowest-level of jumping.
• It has the general form:
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.
3. The ‘goto’ Statement (cont..)
if (number == 1) {
goto skip;
}
cout << "This line will be skipped." << endl;
skip:
cout << "Jumped to label 'skip'" << endl;
return 0;
}
Output:
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;
The ‘return’ Statement(cont…)
• 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.
int main (void)
cout << "Hello World\n";
return 0;