Information Technology Reference
In-Depth Information
Fig. 4.4. Flowcharts for the “for” loop (a)
and “if-then-else” (b). They illustrate the
decision points in the program where
a branch can be made depending on a
check of some condition. The “for” loop
performs a set number of iterations
through the same piece of code that
use different data. The “if-then-else”
branch executes a different piece of
code depending on the result of a test
condition.
(a)
(b)
no
More
iterations?
yes
no
Condition
true?
yes
Statements#1
Statements#2
Statements
it, however, because the pseudocode version of the program omits details not
essential for understanding by people but necessary for a machine to run the
program. Thus we can write a
do
loop using the
for
keyword
for <var> in <sequence>
<statements>
The variable <var> after the keyword
for
is called the
loop index
, and the state-
ments in the body of the
for
loop - <statements> - are executed according to
the number of times specified in the <sequence> portion of the loop heading.
After completing the loop the required number of times, the program goes to
the program statement after the last statement in the body of the loop.
Similarly, we can write an
if
statement as:
if <condition>:
<statements#1>
else:
<statements#2>
If the Boolean condition <condition> is true, the program executes the first set
of statements - <statements#1> - and then jumps to the statement after the
second block of statements - <statements#2>. If the condition is false, the pro-
gram jumps over the first block of statements and executes the second block
of code <statements#2> under the
else
keyword, before carrying on with the
next statement of the program. It is sometimes helpful to visualize these con-
trol structures as diagrams called
lowcharts
, first introduced into computing
by Herman Goldstine and John von Neumann in 1947. Flowcharts use boxes
to represent the different parts of the program with arrows between the boxes
showing the sequence of events. Flowcharts representing the
for
loop and the
if-then-else
flowcharts are shown in
Fig. 4.4
.
Modern programming languages generally do not encourage use of the
go
to
statement. Undisciplined use of
go to
statements often led to very complex
“spaghetti” code that was difficult to understand and debug. In 1968, Edsger
Dijkstra (
B.4.2
) wrote a famous article titled “Go To Statement Considered
Harmful”:
Search WWH ::
Custom Search