Professional Documents
Culture Documents
A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that
serve to specify what has to be done by our program, when and under which circumstances.
Flow of control through any given function is implemented with three basic types of control
structures:
1. Sequential: default mode, Sequential execution of code statements (one line after
another).
2. Selection: used for decisions, branching -- choosing between 2 or more alternative paths.
In C++, these are the types of selection statements:
If
If…else
else…if
switch
3. Repetition: used for looping, i.e. repeating a piece of code multiple times in a row. In
C++, there are three types of loops:
while
do/while
for
The statement parts are the "bodies" of the control structures. The statement after control
structures must be either:
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 { }
An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.
An if statement can be followed by an optional else if...else statement, which is very useful
to test various conditions using single if...else if statement.
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
2. Iteration or Looping
There may be a situation, when you need to execute a block of code several number of
times.
Repetition statements control a block of code to be executed repeatedly for a fixed
number of times or until a certain condition fails.
General from of a loop statement in most of the programming languages:
Ouput:
i. Infinite loop: no matter what you do with the while loop (and other repetition
statements), make sure that the loop will eventually terminates.
ii. Off-By-One Bugs (OBOB): another thing for which you have to watch out in writing
a loop is the so called Off-By-One Bugs or errors. Suppose we want to execute the
loop body 10 times. Does the following code works?