Skip to content

Looping With a Known Loop Count

Just do something 5 times.

Loops With a Known Loop Count

  • A very common looping task in programming is to loop a predetermined amount of times.

  • We can code this with while loops or for loops. They are all equivalent in functionality. However, programmers tend to favor the for loop for this.

  • Let's look at it with the while loop first then the for.

  • Here's a small program that does something exactly 5 times.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
    This function is in file unit04/demos/js/knownLoopCount.js.
    It loops five times with a while loop
*/
function whileFiveTimes() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const LOOP_LIMIT = 5;

    // Declare Variables
    let counter;

    // Initialize the counter
    counter = INITIAL_VALUE;

    while (counter < LOOP_LIMIT) {
        document.write("This is loop number: " + counter + "<br />");
        counter++;
    }
}

  • And here it is with a for loop.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/*
  This function is in file unit04/demos/js/knownLoopCount.js.
  It loops five times with a for loop
*/
function forFiveTimes() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const LOOP_LIMIT = 5;

    // Declare Variables
    let counter;

    for (counter = INITIAL_VALUE; counter < LOOP_LIMIT; counter++) {
        document.write("This is loop number: " + counter + "<br />");
    }
}


They look very similar. The main difference is that the for loop has one less line of code.


For Loop


The while loop does the same thing, only differently.


While Loop


Example: Fahrenheit-Celsius Conversion

Demo

  1. Demo: Fahrenheit-Celsius Conversion
    • unit04/demos/demo-fahrenheit-celsius.html

Not everything that can be counted counts, and not everything that counts can be counted. -Albert Einstein

Read more

Related Reading

Pages 57 - 67

Hands on Work

Labs

  1. Lab05: While Loop with known Count
    • unit04/labs/lab-05-while-known-count.html
  2. Lab06: For Loop with known Count
    • unit04/labs/lab-06-for-known-count.html

Exercises

  1. Lab05 exercise
    • unit04/exercises/exercise-05.html
  2. Lab06 exercise
    • unit04/exercises/exercise-06.html