Section 8 - Iteration
Notes on Iteration
Necessary Vocabulary
-
Iteration - Repitition of a Process
-
For Loop
- FOR LOOP repeats a function for a set number of times; I is the number of times repeated
-
While Loop
- The while loop is used to repeat a section of code an unknown number of times until a specific condition is met
-
Initialization - What sets the counter variable to a starting value. For example (var i = 0) represents an initial value of 0.
- Condition - Allows the computer to know whether or not to keep repeating the loop.
- increment/decrement - Modifies the counter variable after each repetition.
The second type of loop is a REPEAT UNTIL (condition) loop, where the loop will continue to run until a condition is met.
Conceptually, a while loop is very similar to an if conditional, except that a while is continually executed until it's no longer true and an if is only executed once.
Practice
Consider the Following Code Segment. How Many times will print(ln) be called?
for (var i = 1; i <= 10; i++) {
for (var j = 1; j <= 10; j++) {
println(i * j);
}
}
Answer!
[100 Times.The computer will execute the outer for loop 10 times (starting at i = 1 and ending after i = 10). Each time that it executes the outer loop, it will execute the inner for loop 10 times (starting at j = 1 and ending after j = 10). Each inner execution will call println() once.10 times 10 times 1 is 100, so the computer will call println() 100 times.]Practice
Consider the Following Code Segment. What is it initial value? What does the while loop check?
var numRabbits = 2;
var numYears = 0;
while (numRabbits <= 100) {
numRabbits += (numRabbits/2 * 30);
numYears++;
}