Big Ideas

  • Understanding What is Iteration
  • Using for and while loops

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.

What is Iteration?

Iterative statements are also called loops, and they repeat themselves over and over until the condition for stopping is met.

In College Board's Pseudocode, the first is a REPEAT n TIMES loop, where the n represents some number.

Alt text

The second type of loop is a REPEAT UNTIL (condition) loop, where the loop will continue to run until a condition is met.

Alt text

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. What is the Counter Variable and the Condition set as?

    for (var i = 10; i > 0; i--) {
   println(i);
}
Answer! [Counter Variable: 10, Condition: Greater than 0]

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++;
}
Answer! [2 Rabbits.The while loop checks that the number of rabbits is less than 100. As long as the population is less the 100, the code inside the loop continues to run.]

Sources

  • AP College Board/Classrom
  • Khan Academy: APCSP