Sie sind auf Seite 1von 31

Control Structure and

Repetition
By: Group 4
 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. While the terms repetition and iteration
are very descriptive words, the common term to
describe these control structures is loop. 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). I categorize
loops into two general categories:
Indeterminate 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:

Pre-test loops
Post-test loops
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. Below are
diagrams representing of each type of loop:

When considering pre-test loops, the standard
example is the Do-While loop. The general syntax
of the Visual Basic Do-While can be viewed a
couple of ways:
 Do While conditions Do While conditions
{ statement (s) } { statement (s) }
Loop statement affecting condition
Loop
The structure on the left above is technically
correct syntax, but perhaps not logically so.
Technically, a loop body can contain zero
statements; but if that is the case, the loop will
never terminate. A loop that never terminates is
called an infinite loop, and typically is not a
desirable event. The structure above on the right
mandates at least one statement that will affect
the condition, thus hopefully causing the loop to
end. Once the loop ends, program execution
will continue at the first statement following the
end of the loop.
 The condition in any loop must evaluate to a
Boolean value; as always, either True or False. The
condition in a loop will be similar to the logic and
syntax used in an If-Then statement. That is, the
condition will consist of relational and/or logical
operators. It is the condition that is perhaps the most
difficult part of a loop; if the logical condition is
incorrect, there is little hope that the loop will
produce the desired results. It is also of import that
the condition which will cause the loop to terminate
must occur. Looking at a Do-While loop structure
whose task is to sum the numbers between 1 and 5,
we can observe the following (note the numbers to
the left are for descriptive purposes only):
In computer science,
the Boolean data type is a data type
that has one of two possible values
(usually denoted true and false),
intended to represent the two truth
values of logic and Boolean algebra.
It is named after George Boole, who
first defined an algebraic system of
logic in the mid 19th century.
1.Dim intCount As Integer = 1
2.Dim intSum As Integer
3.Do While intCount <= 5
4.intSum = intSum + intCount
5.intCount = intCount + 1
6.Loop
Looking closer at each numbered
statement above:
 statement 1 declares an Integer variable, intCount, and initializes it to 1. This
will be used as our counter or control variable, which will allow termination
of the loop.
 statement 2 declares another Integer variable to be used to store our
summary total (i.e. sum). It is not intialized, but recall any variable not
specifically initialized is set to zero by VB.
 statement 3 is the start of our Do-While loop construct. Note that our logical
condition here is intCount <= 5. It should be understood that the condition
intCount <= 5 must be True for the loop body to continue to execute.
 statement 4 accumulates the value of intCount into intSum.
 statement 5 increments the counter; it is this statement that will eventually
cause our condition to be False.
 finally, statement 6 is the formal end to the loop.
Below is a table of values for each variable
as well as the corresponding Boolean
condition as the loop iterates:
intCount intSum intCount <= 5 Comment

initial values as loop


1 0 True
entered

2 1 True start of pass 2

3 3 True start of pass 3

4 6 True start of pass 4

5 10 True start of pass 5

6 15 False loop terminates


As you can see from above, when the value of
intCount becomes 6, the relational condition
returns a False value, and loop execution
terminates.
As stated previously, the difficulty with loops is
the logic which is required to make them work
correctly. Consider the following simple
modification to statement 3 above:

Do While intcount < 5


 Do you notice this difference? Since intCount is initialized (by
default) to zero and the incrementing statement being inside the
loop, this will result in the loop body never getting executed. This
logic error will result in a value of 0, which is perhaps even worse.
Pay very close attention to the logical details when working with
loops and relational operators!

 When considering post-test loops, the standard example is the Do-


Until loop. The general syntax of the Visual Basic Do-Until can be
viewed a couple of ways:

Do Do
[ statement (s) ] [ statement (s) ]
Loop Until condition statement affecting condition
Loop until condition
 As above, the structure on the left above is technically correct
syntax, but perhaps not logically so. Technically, a loop body can
contain zero statements; but if that is the case, the loop will never
terminate. Notice here the condition is checked at the bottom of
the loop, thus the loop body will always be executed at least once.
Looking at a similar Do-Until loop to sum the numbers between 1
and 5, we observe:

1. Dim intCount As integer = 1


2. Dim intSum As integer
3. Do
4. intSum = intSum + intCount
5. intCount = intCount + 1
6. Loop Until intCount > 5
 Most of the logic here is similar to the Do-While loop above.
However, notice the correlation between the relational operator in
the Do-While and the one in the Do-Until. Do you understand this
correlation?

When considering determinate loops, the standard example is


the For-Next loop (note that this is also a pre-test loop). The general
syntax of the Visual Basic For-Next is as follows:

For counter = start_value To end_value [Step step_value]


[statement (s)]
Next [counter]
This looping structure appears a bit more complicated
than the other two, simply because there are more
components. Looking at the components individually, we
see:
 counter - the control variable for the loop, initially set to start_value,
and holding values through (and past) the end_value, as specified
by the optional step_value. The data type ofcounter is usually
Integer but can be any type that supports the >=, <=, +, and -
operators.
 start_value - the initial value for the counter. This value is assigned
before the loop iteration begins.
 end_value - the terminating value for the counter. This value will be
the final value for the counter within the loop; but will be
larger/smaller outside the loop, depending uponstep_value.
 step_value - optional, the amount by which counter is incremented
each iteration through the loop. If omitted, the step_value defaults
to 1. When specified, this value may be positive or negative.
 As the execution of the For-Next loop begins, VB evaluates start_value,
end_value, and step_value. The start_value is then assigned to
the counter variable. Before execution of the For-Next body, the counter is
compared to the end_value. If counter is already greater than (for a
positive step_value or less than for a negative step_value) the end value,
the For-Next loop terminates and control is passed to the statement
following the Next statement; otherwise the statement block is executed.
This algorithm for the For-Next loop can be summarized as follows:
1. initialize counter variable to start_value
2. evaluate counter <= end_value if positive step_value or 1
evaluate counter >= end_value if negative step_value
3. if step 2 returns True, execute body statements, if False terminate loop
4. increment counter by step_value (or 1 if none specified)
5. Go to step 2
As with the above summation examples
above, below is an equivalent For-Next
loop:
Dim intCount As integer
Dim intSum As integer

For intCount = 1 To 5
intSum = intSum + intCount
Next
 Which achieves and equivalent result. One important difference to
note from the other two loop structures is that in a For-Next loop, the
increment of the control variable happens automatically. That is,
incrementing the counter variable is built in to the loop behavior
(note this is step # 5 in the two loop examples above). This is
commonly a confusing point for students.
 As in the examples above, the value of intSum upon termination of
this loop would be 15. However, it is important to look at the value
intCount would have upon loop termination. As this loop will only
terminate when intCount > 5, the value of that variable would then
be 6. Any usage of this variable will result in using the value 6. This is
a very important side effect of all loops in general.
 Note you could also write the above For loop as:
For intCount = 5 To 1 Step -1
and achieve an equivalent result, however this may be logically
more difficult to understand.
When looking at the following two For statements,
we might ask the simple question "how many times
will each loop, loop?"
 For intCount = -5 To 5
 For intCount = 0 To 15 Step 2

While we might be able to calculate the result using our fingers, a more
accurate approach is by using the following formula to calculate exactly how
many iterations a loop will perform:
# iterations = Int2((end_value - start_value) / step_value) + 1
Which when step_value = 1 simplifies to
# iterations = end_value - start_value + 1
Thus, in the example # 1 above, the number of iterations would be:
(5 - -5) + 1 or 11
and example # 2 would result in
Int ((15 - 0) / 2) + 1, or 8
Make sure you clearly understand how each of these results were found.
Note this step implies if start _value > end_value and step_value> 0, the For-Next
loop will iterate zero times. The same is true for the logical inverse of this.
Control structures

Programs written in procedural languages, the most common


kind, are like recipes, having lists of ingredients and step-by-step
instructions for using them. The three basic control structures in
virtually every procedural language are:
 1. Sequence—combine the liquid ingredients, and next add
the dry ones.
 2. Conditional—if the tomatoes are fresh then simmer them,
but if canned, skip this step.
 3. Iterative—beat the egg whites until they form soft peaks
Sequence is the default control structure; instructions are
executed one after another. They might, for example, carry out
a series of arithmetic operations, assigning results to variables, to
find the roots of a quadratic equation ax2 + bx + c = 0.
The conditional IF-THEN or IF-THEN-ELSE control structure allows a
program to follow alternative paths of execution. Iteration, or
looping, gives computers much of their power. They can repeat
a sequence of steps as often as necessary, and appropriate
repetitions of quite simple steps can solve complex problems.
These control structures can be combined. A sequence may
contain several loops; a loop may contain a loop nested within
it, or the two branches of a conditional may each contain
sequences with loops and more conditionals. In the
“pseudocode” used in this article, “*” indicates multiplication
and “←” is used to assign values to variables. The following
programming fragment employs the IF-THEN structure for finding
one root of the quadratic equation, using the quadratic formula:
The quadratic formula assumes that a is nonzero and that the
discriminant (the portion within the square root sign) is not negative
(in order to obtain a real number root). Conditionals check those
assumptions:

IF a = 0 THEN
ROOT ← −c/b
ELSE
DISCRIMINANT ← b*b − 4*a*c
IF DISCRIMINANT ≥ 0 THEN
ROOT ← (−b + SQUARE_ROOT(DISCRIMINANT))/2*a
ENDIF
ENDIF
The SQUARE_ROOT function used in the above fragment
is an example of a subprogram (also called a procedure,
subroutine, or function). A subprogram is like a sauce
recipe given once and used as part of many other
recipes. Subprograms take inputs (the quantity needed)
and produce results (the sauce). Commonly used
subprograms are generally in a collection or library
provided with a language.
Subprograms may call other subprograms in their definitions, as
shown by the following routine (where ABS is the absolute-value
function). SQUARE_ROOT is implemented by using a WHILE
(indefinite) loop that produces a good approximation for the
square root of real numbers unless x is very small or very large. A
subprogram is written by declaring its name, the type of input data,
and the output:
 FUNCTION SQUARE_ROOT(REAL x) RETURNS REAL
 ROOT ← 1.0
 WHILE ABS(ROOT*ROOT − x) ≥ 0.000001
 AND WHILE ROOT ← (x/ROOT + ROOT)/2
 RETURN ROOT
Subprograms can break a problem into smaller, more tractable
subproblems. Sometimes a problem may be solved by reducing it
to a subproblem that is a smaller version of the original. In that case
the routine is known as a recursive subprogram because it solves
the problem by repeatedly calling itself. For example, the factorial
function in mathematics (n! = n∙(n−1)⋯3∙2∙1—i.e., the product of
the first n integers), can be programmed as a recursive routine:

 FUNCTION FACTORIAL(INTEGER n) RETURNS INTEGER

 IF n = 0 THEN RETURN 1

 ELSE RETURN n * FACTORIAL(n−1)


The advantage of recursion is that it is often a simple restatement of
a precise definition, one that avoids the bookkeeping details of an
iterative solution.

At the machine-language level, loops and conditionals are


implemented with branch instructions that say “jump to” a new
point in the program. The “goto” statement in higher-level
languages expresses the same operation but is rarely used
because it makes it difficult for humans to follow the “flow” of a
program. Some languages, such as Java and Ada, do not allow it.

Das könnte Ihnen auch gefallen