Iteration (or Repetition)



index
Disabled back button Next Section
printable version

Section 1: Introduction

The main strength of any programming language is its ability to process blocks of code repeatedly.

A loop is a control structure that allows a statement or a block of statements to be repeated multiple times.

Repetition can be implemented as:

Pre-test loops while structure
Post-test loops do/while structure
Count-controlled loops for structure
Section 2: while loop: Pre-Test Repetition Structure

In pre-test loops the condition is checked before the body of the loop is executed.

JavaScript provides the while structure for pre-test loops.

While there are more items on my shopping list
     Purchase next item and cross it off my list

See an animated demo of a While statement.

Example: find the first power of 2 larger than 1000.

var product = 2;

while (product <= 1000)
{
   product = product * 2;
}

while structure
Common Programming Error

A common error is failing to include in the body of a while structure an action that eventually causes the condition in the while to become false. This will normally result in a repetition structure that will never terminate-an error caIled an "infinite loop."
Section 3: do/while loop: Post-Test Repetition Structure

In post-test loops the condition is checked after the body of the loop is executed.

JavaScript provides the do/while loop structure to implement a post test.

Since the do/while repetition structure tests the loop-continuation condition after the loop body is performed, the loop body will be executed at least once.

See an animated demo of a Do/While statement.

Example: reverse a number

num = document.getElementById("txtNum").value;

do
{
    nextDigit = num % 10;        // strips off last digit
    reversed += nextDigit;        // concatenates last digit to reversed
    num = parseInt(num / 10); // removes the last digit from num
}
while (num > 0)

Number Reverser Demo

do loop structure

Note that the loop-continuation condition is not tested until after the action is performed at least once.

Testing and Debugging Tip

Infinite loops are caused when the loop-continuation condition never becomes false. In a count-controlled loop make sure the control variable is incremented (or decremented) in the body of the loop. 
Section 4: Count-Controlled Loops

Count-controlled loops require:

  1. The name of a loop control variable (or loop counter)
  2. The initial value of the control variable.
  3. The increment (or decrement) by which the control variable is modified each time through the loop.
  4. The condition that tests for the final value of the control variable (i.e., whether looping should continue).

Example:

var beginCelsius = +document.getElementById("txtBeginning").value;
var endCelsius = +document.getElementById("txtEnding").value;

var celsius = beginCelsius;

while (celsius <= endCelsius)
{
    fahrenheit = (celsius * 9/5) + 32;
    cOutput += celsius + "\n";
    fOutput += fahrenheit + "\n";
    celsius = celsius + 1;
}

The loop terminates when the control variable exceeds endCelsius.

See an animated demo of a For statement.


Common Programming Error

Because floating-point values may be approximate, controlling counting loops with floating point variables may result in imprecise counter values and inaccurate tests for termination. (Because JavaScript does not distinguish between integer and real numbers, this is not a major problem. However, it is safer to use a relational operator other than == to specify the loop termination condition.)


for Repetition Structure

The for repetition structure handles all the details of count-controlled repetition.

The previous procedure is rewritten as a for loop below.

Example:

var beginCelsius = +document.getElementById("txtBeginning").value;
var endCelsius = +document.getElementById("txtEnding").value;

for (var celsius=beginCelsius; celsius<=endCelsius; celsius++)
{
    fahrenheit = (celsius * 9/5) + 32;
    cOutput += celsius + "\n";
    fOutput += fahrenheit + "\n";
}


An example of a for loop can be viewed in the Celcius Equivalents demo.


The loop continues as long as the control variable is less than or equal to the final value.

Notes:

for/next structure

Special for notes:

Testing and Debugging Tip

Although the value of the control variable can be changed in the body of a for loop, avoid doing so because this practice can lead to subtle errors.


for/next flowchart

Note that the initialization occurs only once and that incrementing occurs each time after the body is executed.


Examples:

Section 5: Breaks not allowed!

Avoid the use of break statements to terminate loop execution.

Avoid doing this!

const numGrades = 5;
var grade;
for (var counter = 1; counter <= numGrades; counter++)
{
     grade = prompt("Enter grade:", "00");
     if (grade < 60)
     {
          alert("Failing grade encountered.");
          break; // avoid using this in a for loop!
     }
}

if (counter > numGrades)
{
     alert(" Excellent!\nAll students passed!");
}


Better approach, because a for loop is designed to be a count-controlled loop, and it is expected that it will terminate ONLY when the test condition becomes false. There should be a single exit ONLY!

const numGrades = 5;
var grade;
var allGradesPassed = true;
var counter = 0;

while ((counter <= numGrades) && allGradesPassed)
{
     grade = prompt("Enter grade:", "00");
     if (grade < 60)
     {
          alert("Failing grade encountered.");
          allGradesPassed = false;
     }
     counter += 1;
}

if (allGradesPassed)
{
     alert(" Excellent!\nAll students passed!");
}

Why no breaks?