Control Structures
Control Structures
Flow of Control:
Flow of control through any given function is implemented with three basic types of control structures:
Sequential: default mode. Sequential execution of code statements (one line after another) -- like following a
recipe
Selection: used for decisions, branching -- choosing between 2 or more alternative paths. In C++, these are the
types of selection statements:
if
if/else
switch
Repetition: used for looping, i.e. repeating a piece of code multiple times in a row. In C++, there are three types
of loops:
o
while
do/while
for
The function construct, itself, forms another way to affect flow of control through a whole program. This will be discussed
later in the course.
Some useful tools for building programs or program segments
Selection and repetition statements typically involve decision steps. These steps rely on conditions that are
evaluated as true or false
C++ has a boolean data type (called bool) that has values true and false. Improves readability.
Most functions that answer a yes/no question (or a true/false situation) will return a boolean answer (or in the case
of user-defined functions, they should be coded that way)
Important: ANY C++ expression that evaluates to a value (i.e. any R-value) can be interpreted as a true/false
condition. The rule is:
o
Logical Operators:
The arithmetic comparison operators in C++ work much like the symbols we use in mathematics. Each of these operators
returns a true or a false.
x
x
x
x
x
x
== y
!= y
< y
<= y
> y
>= y
//
//
//
//
//
//
x
x
x
x
x
x
is
is
is
is
is
is
equal to y
not equal to
less than y
less than or
greater than
greater than
y
equal to y
y
or equal to y
We also have Boolean operators for combining expressions. Again, these operators return true or false
x && y
x || y
!x
These operators will be commonly used as test expressions in selection statements or repetition statements (loops).
Examples of expressions
(x > 0 && y > 0 && z > 0)
(x < 0 || y < 0 || z < 0)
The && and || operators also have a feature known as short-circuit evaluation.
In the Boolean AND expression (X && Y), if X is false, there is no need to evaluate Y (so the evaluation stops).
Example:
(d != 0 &&
n / d > 0)
Similarly, for the Boolean OR operation (X || Y), if the first part is true, the whole thing is true, so there is no
need to continue the evaluation. The computer only evaluates as much of the expression as it needs. This can
allow the programmer to write faster executing code.
Selection Statements
The most common selection statement is the if/else statement. Basic syntax:
if (expression)
statement
else
statement
if (expression)
statement
The expression part can be any expression that evaluates a value (an R-value), and it must be enclosed in
parintheses ( ).
o
The best use is to make the expression a Boolean expression, which is an operation that evaluates to true
or false
The statement parts are the "bodies" of the if-clause and the else-clause. The statement after the if or else clause
must be either:
o
an empty statement
;
a single statement
expression;
a compound statement (i.e. a block). Can enclose multiple code statements. Remember, a compound
statement is enclosed in set braces { }
Appropriate indentation of the bodies of the if-clause and else-clause is a very good idea (for human readability),
but irrelevant to the compiler
Examples
// Notice that there is no else clause. If the grade is below 68, we move on.
if (x == 0)
cout << "Nothing here";
else
cout << "There is a value";
// This example contains an else clause. The bodies are single statements.
if (y != 4)
{
cout << "Wrong number";
y = y * 2;
counter++;
}
else
{
cout << "That's it!";
success = 1;
}
Multiple statements are to be executed as a result of the condition being true or false. In this case, notice the compound
statement to delineate the bodies of the if and else clauses.
Be careful with ifs and elses. Here's an example of an easy mistake to make. If you don't use { }, you may think that
you've included more under an if condition than you really have.
// What output will it produce if val = 2? Does the "too bad" statement really go with the "else" here?
if (val
cout
else
cout
cout
< 5)
<< "True\n";
<< "False\n";
<< "Too bad!\n";
* Indentation is only for people! It improves readability, but means nothing to the compiler.
Example links
if (x == 1 || 2 || 3)
A switch statement is often convenient for occasions in which there are multiple cases to choose from. The syntax
format is:
switch (expression)
{
case constant:
statements
case constant:
statements
...
default:
statements
// optional label
The switch statement evaluates the expression, and then compares it to the values in the case labels. If it finds a
match, execution of code jumps to that case label.
The values in case labels must be constants, and may only be integer types, which means that you
o
This means only integer types, type char, or enumerations (not yet discussed)
This also means the case label must be a literal or a variable declared to be const
Note: You may not have case labels with regular variables, strings, floating point literals, operations, or
function calls
If you want to execute code only in the case that you jump to, end the case with a break statement, otherwise
execution of code will "fall through" to the next case
Examples:
o
Switch Example 1 -- An attempt to convert the letter grade example into a switch. Syntactically correct,
but has a logic flaw. What is it?
Switch Example 3 -- Uses a switch statement to process a menu selection, using both upper and lower
case options
Format:
test_expression ? true_expression : false_expression
How it works:
o
The test_expression is evaluated for true/false value. This is much like the test expression of an ifstatement
Note that this operator takes three operands. It is the one ternary operator in the C++ language
Example 1:
cout << (x > y ? "x is greater than y" : "x is less than or equal to y");
// Note that this expression gives the same result as the following
if (x > y)
cout << "x is greater than y";
else
cout << "x is less than or equal to y";
Example 2:
(x < 0 ? value = 10 : value = 20);
// this gives the same result as:
value = (x < 0 ? 10 : 20);
// and also gives the same result as:
if (x < 0)
value = 10;
else
value = 20;