Count Controlled For Loop

For LoopThe loops encountered so far are used when the number of times a loop is to be executed is unknown.  Looping continues while some condition holds, and exit from the loop may happen the first time or 1000th time round the loop.

If we knew how many times a loop is to be executed we can use another type of loop, the for loop. Loops with a predetermined number of iterations are very common, and they all have a loop control variable to count the iterations.

The loop control variable is given an initial value by the first expression, and once inside the loop it is incremented or decremented.  The loop is terminated when the control variable has passed its final value.

// Example code for a For Loop
var Number ;
var Total = 0 ;
var Count ;

for (Count=1;Count<=5;Count++)
{  // begin for

Number = prompt('Type in a number: ');
Number = parseInt(Number);

Total = Total + Number;

alert ('Count = ' + count + '\n' + 'Total = ' + Total) ;

} // end for

Next: Choosing the Appropriate Loop