Control Structures
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.
[Three control structures, namely, the sequence structure, the selection structure and
the repetition structure. The term "control structures" comes from the field of computer
science. When we introduce C++'s implementations of control structures, we'll refer to
them in the terminology of the C++ standard document2 as "control statements."]
A computer can process a program in one of the following ways: in sequence;
selectively, by making a choice, which is also called a branch; repetitively, by executing
a statement over and over, using a structure called a loop; or by calling a function.
Control structures provide alternatives to sequential program execution and are used to
alter the sequential flow of execution. The two most common control structures are
selection and repetition. In selection, the program executes particular statements
depending on some condition(s). In repetition, the program repeats particular statements
a certain number of times based on some condition(s).
PHYS-204 Rashed-Nizam
Selection structure
If – else condition:
There come situations in real life when we need to make some decisions and based on
these decisions, we decide what we should do next. Similar situations arise in
programming also where we need to make some decisions and based on this decision
we will execute the next block of code. Decision making statements in programming
languages decides the direction of flow of program execution.
➢ Sequence structures execute statements one after another without changing the flow
of the program.
➢ Other structures, such as the ones that make decisions, do change the flow of the
program.
➢ The structures that make decisions in C++ programs are called selection structures.
➢ When a decision is made in a program, a selection controls the flow of the program
based on the decisions in the program.
➢ The if structure is a one-way selection structure. When a control expression in an if
statement is evaluated to be true, the statements associated with the structure are
executed.
➢ The if/else structure is a two-way selection structure. If the control expression in the
if statement evaluates to true, one block of statements is executed; otherwise (else),
another block is executed.
➢ The switch structure is a multi-way selection structure that executes one of many
sets of statements, depending on the value of the control expression. The control
expression must evaluate to an integer or character value.
PHYS-204 Rashed-Nizam
For decision making in C++, we have four types of control statements (or control
structures), which are as follows:
Operator Description:
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
! not
&& and (two ampersands)
|| or (two pipe)
PHYS-204 Rashed-Nizam
Structure of the if:
if ( condition )
statement;
❖ The curly brackets are not required if you only want one statement to be executed
when the control expression is true.
Condition style:
– Use the symbols { and } to group several statements as a single unit.
– Simple statements within the compound statements end with semicolons.
– Compound Statements are sometimes called a statement block.
– Use compound statements in an if statement if you want several actions
executed when the Boolean expression is true.
PHYS-204 Rashed-Nizam
If/else structure:
if (condition)
statement;
else
statement;
➢ The if/else structure is sometimes called a two-way selection structure.
➢ Using if/else, one block of code is executed if the control expression is true.
➢ The else portion of the structure is executed if the control expression is false.
➢
PHYS-204 Rashed-Nizam
Nested if Structures:
➢ You can place if structures within other if structures.
➢ When an if or if/else structure is placed within another if or if/else structure, the
structures are said to be nested.
➢ The flowchart in Figure 8-3 decides whether a student is exempt from a final exam
based on grade average and days absent.
** I prefer that you avoid Nested if statements and use compound Boolean Expressions
whenever possible.
Switch Structure:
➢ C++ has another method of handling multiple options known as the switch structure.
➢ The switch structure has many uses but is most often used with menus.
➢ Nested if/else structures could be used in place of the switch structure.
➢ The switch structure is easier to use and a programmer is less prone to making errors
that are related to braces and indentations.
➢ Remember, however, that an integer or character data type is required in the control
expression of a switch structure.
➢ When using character types in a switch structure, enclose the characters in single
quotation marks as in any other character literal.
➢ Use a : (colon) after each case statement, not a ; (semi-colon).
PHYS-204 Rashed-Nizam
Repetition structure
Repetitive control structures, also referred to as iterative structures, are groupings of
code which are designed to repeat a set of related statements. This repetition (or
iteration) can repeat zero or more times, until some control value or condition causes the
repetition to cease. We use iterative controls when we need to do the same task more
than once, based upon some logical condition.
A repetition control structure will execute a block of code a number of times based on
some condition. In the world of programming, we generally will use two types of
repetition control structures: counting and conditional. We commonly refer to
repetition control structures as loops.
➢ Loops consist of two logical parts; the condition (i.e. the logic that evaluates the
condition), and the loop body (i.e. where the code integral to the loop is located).
➢ While the terms repetition and iteration are very descriptive words, the common
term to describe these control structures is loop
1. indeterminate loops
2. determinate loops
• The difference being that with a determinate loop structure, one can (normally)
predict exactly how many times the loop will repeat;
• whereas with an indeterminate loop structure, this is not always the case. An
indeterminate loop structure loops as long as a condition evaluates to some
certain Boolean value.
• Indeterminate loops should be used when the programmer does not know
exactly how many times the iteration need occur. Logically however, both
indeterminant and determinate loops can be written to be equivalent.
Beginning with indeterminate looping structures, there are two types to introduce:
1. pre-test loops
2. post-test loops
PHYS-204 Rashed-Nizam
❖ A pre-test loop evaluates its condition before any statements contained in its body
are executed. Thus, a pre-test loop can execute its body a minimum of zero times,
assuming the initial value of the condition evaluates to False.
❖ A post-test loop on the other hand, evaluates its condition after it executes all
statements in its body. Thus, a post-test loop can execute its body a minimum of
one time, even if the initial value of the condition evaluates to False.
o The While Loop
To start, we will first explore the while loop. The loop is considered a conditional loop
because it bases the number of iterations the condition.
• The syntax for the while loop is straight-forward and can be seen in the diagram
below.
while(condition)
{
statement
}
➢ The while loop is considered as pre-test loop because it first test the condition, and if
the condition is true, it executes the statement.
➢ It will continue to execute the statement until the condition is false.
PHYS-204 Rashed-Nizam
➢ It is important to note that if the condition never becomes false, the statement will continue
to execute. This is what we refer to as an endless loop, and is generally, bad
programming practice.
➢ If the condition is false the first time the while loop condition is tested, it will never execute
the statement. This is why we say that a while loop has a zero to N range, where N is some
number.
o The do_while loop:
The next repetition control structure that we need to explore is the do-while loop,
which is also considered a conditional loop.
➢ The do-while loop works much the same way the while loop works with one
fundamental differences: the do-while loop is a post test loop.
➢ In contrast, the while loop first tested the condition, then executed the statement after
determining the condition was true; hence, the phrase pre test loop.
➢ The syntax for the do-while loop can be seen in the figure below.
do{
statement
}while(condition)
PHYS-204 Rashed-Nizam
Flow chart for while and do_while loop:
o The For Loop
The final loop that we are going to investigate in this chapter is the for loop - our
first and only counting loop.
➢ The for loop is called a counting loop because it executes a number of times
(which is still a condition) rather than on a condition.
➢ The for loop is an extremely handy control structure for working with lists of
information, such as arrays.
➢ The for loop is a little more sophisticated than the while and do while
loop. It also has a more complicated syntax as can be seen in the figure
below.
for(initialization; condition; increment)
{
statement
}
➢ The for loop has three different sections to worry about in addition to the
statement: initialization, condition, and increment.
➢ The initialization section is for initializing a variable to a starting value and is
the first thing executed. The initialization only executes once.
➢ The condition is similar to the other loops. The for loop would be considered
a pre test loop.
PHYS-204 Rashed-Nizam
➢ Finally, there is the increment section which is executed after the statement.
➢ Both the condition and increment are executed multiple times based on the
number of times the for loop will execute.
PHYS-204 Rashed-Nizam
PHYS-204 Rashed-Nizam
Arrays
Before formally defining an array, let us consider the following problem. We want to
write a C++ program that reads five numbers, finds their sum, and prints the numbers in
reverse order.
PHYS-204 Rashed-Nizam
An array is a collection of elements of the same type placed in contiguous memory
locations that can be individually referenced by using an index to a unique identifier.
Five values of type int can be declared as an array without having to declare five
different variables (each with its own identifier).
For example, a five element integer array foo may be logically represented as;
where each blank panel represents an element of the array.
➢ In this case, these are values of type int. These elements are numbered from 0 to 4,
with 0 being the first while 4 being the last;
➢ In C++, the index of the first array element is always zero. As expected, an n array
must be declared prior its use. A typical declaration for an array in C++ is:
type name [arraySize] = { , , , , };
➢ where type is a valid type (such as int, float ...), name is a valid identifier and the
arraySize field (which is always enclosed in square brackets []), specifies the size of
the array.
PHYS-204 Rashed-Nizam
Strings
The term string generally means an ordered sequence of characters, with a first
character, a second character, and so on, and in most programming languages such
strings are enclosed in either single or double quotes.
In C++ the enclosing delimiters are double quotes. In this form the string is referred to
as a string literal and we often use such string literals in output statements when we
wish to display text on the screen for the benefit of our users.
PHYS-204 Rashed-Nizam