Lesson 2.3 Looping
Lesson 2.3 Looping
CONTROL STATEMENTS
AND FUNCTIONS
Lesson 2.3
LOOPING
Objectives:
At the end of the lesson, you should be able to:
1. Create Loops using For-Next Statements and
2. Control the number of iterations in a loop
using Step.
Loops
At instances when we want the computer to do
a task repeatedly for a certain number of times,
looping becomes necessary. Note that this is not
the same as having a user re-enter a value until a
valid value is given (like our SK program in
Lesson 2.2). In such a case it is the user doing the
repeated task, not the computer. The loop was
first conceptualized by Ada Byron (recall Lesson
1.1).
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
x > end_val
add an * to 1stLoop
x = x + incr
end
No
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Continuation
Nesting Loops
In the previous lesson, we found that we can nest
If statements. We can do the same for For-Next.
The rules of nesting still apply, of course.
Nesting Loops
Continuation
Here is an example:
For A = 1 To 5
For B = 1 to 10
(Statements)
Next
Next
In this example, for every loop of A, B has made ten
loops. Since A will loop five times, the statements
bounded by the B loop would have been repeated
fifty times!
Other Loops
Aside from For-Next, there are other looping
statements that can be used. The three sets of
code outlined below are essentially the same.
For K = 5 to 10 Step 2
(Repeated Statements)
Next
Other Loops
K=5
While K < = 10
(Repeated Statements)
K=K+2
Wend
Continuation
Other Loops
Continuation
K=5
Do While K < = 10
(Repeated Statements)
K=K+2
Loop
The last two sets of code are more literal
translations of the flowchart that was shown
earlier.