Learning objectives
- Write C++ programs making good use of conditional statements
- Write C++ programs making good use of iteration statements
Programs are said to have a flow of control, the order in which the program statements are executed. Normally in procedural programs, the flow of control is sequential, i.e the first statement is executed then the second and so on. Control structures are statements that allow the programmer to alter the normal flow of control. There are three basic types of control structure:
These allow conditional execution. A variable can be tested with a particular condition. If this condition is met then the flow of control can be changed to an alternate set of statements.
In the Matlab module if
statements were introduced and they have a similar syntax in C++. Below (temperature > 37.5)
represents the conditional expression, which evaluates to either true or false. It is grouped together with statements in curly brackets to form a compound statement.
if (temperature >37.5) {
hyperthermic = true;
cout << "Warning - patient in danger!" << endl;
}
else {
hyperthermic = false;
cout << "Patient normal" << endl;
}
There is also an optional second part to the C++ if
statement. If the conditions aren’t satisfied in the if
statement an else
statement can be used to carry out a different function.
The C++ if-else
statement requires conditional expressions to be specified. Any of the following comparison operators can be used in C++ conditional expressions:
Comparison Operators | Logical Operators |
---|---|
== equal to |
&& and |
!= not equal to |
|| or |
> greater than |
! not |
< less than |
|
>= greater than or equal to |
|
<= less than or equal to |
Note the different inequality operator in C++ compared to Matlab. Matlab uses ~=
for inequality whereas C++ uses !=
.
All of the logical operators mentioned above are subject to rules concerning operator precedence when evaluating complex expressions in the same way that arithmetic operators are. The following table shows the order of operator precedence for both arithmetic and logical operators:
Precedence | Operators |
---|---|
1st | ++ -- ! |
2nd | * / % |
3rd | + - |
4th | < <= > >= |
5th | == != |
6th | && |
7th | || |
It is possible to nest control structures in C++, i.e. include one control structure statement inside another. e.g.
if (temperature > 37.5) {
hyperthermic = true;
hypothermic = false;
}
else {
if (temperature < 35)
hypothermic = true;
else
hypothermic = false;
hyperthermic = false;
}
Note how in the example above {}
are omitted. Curly brackets are only optional when a single statement will be executed after the conditional expression.
Make sure the nested statements are indented correctly. Properly indenting nested statements significantly improves readability.
A switch
statement offers an easy way of coding situations where the same variable needs to be checked against a number of different values.
switch (expression) {
case constant-1:
statement-a;
statement-b;
break;
case constant-2;
statement-c;
statement-d;
break;
case constant-3;
statement-e;
statement-f;
break;
}
The switch
statement is used only for equality tests - it cannot be used for other comparisons (e.g. >
, <
, etc). The effect of the break
statement is to transfer control of the statement immediately following the switch
statement. The default
label is an optional case which is executed if no case
label is matched.
char c;
cout << "Enter letter:\n";
cin >> c;
switch (c)
{
case ‘A’:
case ‘a’:
cout << "Letter A\n";
break;
case ‘B’:
case ‘b’:
cout << "Letter B\n";
break;
...
default:
cout << "Not a letter\n";
};
Note that in the above example, the break
statement is omitted from certain case
statements, in order for the same piece of code to be executed for more than one label i.e. if both case ‘A’ and ‘a’ are matched. Also notice the use of \n
which is the newline character and has the same effect as endl
.
The second type of control structure is the iterative statement. Iterative statements are useful to execute the same piece of code a number of times.
The for
statement will repeat a section of code for a specified number of iterations. They have basic form:
for (init-stmnt; condition; update-stmnt)
body-statement;
Usually, init-stmt
is used to initialise a control variable, which changes its value in each iteration of the for
statement. The iteration will continue until the condition
becomes false. update-stmnt
is generally used to update the value of the control variable. The following example shows the for
statement in action:
int i;
for (i = 1; i <= 10; i++)
cout << i * i <<endl;
while
loops will repeat a section of code until a condition is satisfied. They should be used when the number of iterations is unknown. They have basic form:
while (condition)
statement;
The statement
is executed so long as the expression
evaluates to true. The following example uses a while
statement to read in a sequence of numbers from the user and print out the square of each one:
int i;
cout << "Enter numbers, Ctrl-D to terminate" << endl;
while (cin >> i)
cout << "Square of " << i << " is " << i * i << endl;
The do statement is similar to a while
loop, as it should be used when the number of iterations is unknown. With the do
loop the statement
is guaranteed to be executed at least once as the expression
is only checked after the first iteration. The general form of a do
loop is:
do
statement;
while (condition);
The following code uses a do
loop to print out a sequence of numbers, each half the value of the previous, until the number becomes less than 0.01.
float i = 1.0;
do {
cout << i << endl;
i /= 2;
} while (i > 0.01);
Note the use /=
operator. The statement i /= 2
is just short for i = i / 2
. This short form can be used for any of the 4 main arithmetic operators i.e. *=
, +=
, -=
, /=
.
Another way of altering the flow of control of a program is to use a jump statement. The effect of a jump statement is to unconditionally transfer control to another part of a program. C++ provides three different jump statements: break
, continue
and goto
.
A break
statement terminates the directly enclosing while
, do
, for
or switch
block. Execution resumes immediately following the terminated block.
The continue
terminates the current iteration of the directly enclosing while
, do
or for
loop. Execution resumes with evaluation of the loop control evaluation.
The goto
statement transfers control unconditionally to any location marked with a label. goto mylabel
will transfer control to this statement, mylabel: "some statement"
. It is not encouraged and should be avoided because it reduced readability and makes the code far more confusing.