Science, Maths & Technology
Author:

# Introducing the 'for' Loop

Updated Monday 29th June 2015

Find out about another way to program repetition, for loops.

## Introduction  Copyright free: Startupstockphotos via Pixabay We'll now introduce you to the for statement (often called a for loop) which enables you to repeat the execution of a block of statements a predetermined number of times, as well as revise the use of the charAt() string method and introduce the length property.

In the examples of repetition we've looked at so far, we didn't know in advance how many times the code in the body of the loop would be executed. The number of iterations was controlled by the while condition and depended, for example, on how many times the user entered invalid data, or how many values were input before the terminating sentinel. The for statement is controlled by a counter, and can be used only when the number of repetitions is known before execution of the statement. For example, if you wanted to calculate the average exam mark for a class of 20 students, you know that you would need to add a mark to the total exactly 20 times before dividing the total number of marks by 20.

In order to control the number of repetitions, for loops use a variable as a counter. To use a JavaScript for loop, you need to know:

• the starting value of the counter;
• the final value of the counter for which the loop body is executed;
• the fixed number by which the counter is increased or decreased after each repetition;
• the statement(s) which make up the body of the loop (as for a while loop).

We'll look at these now in our first activity.

## Activity 1

In this activity, you will study a very simple example of a for loop using for_activity_1.html, replicated below with the structure of the loop highlighted. (a) What do you think the for loop does? Run the program and find out.

(b) What is the value of count once the required number of iterations has been executed?

(a) For each iteration of the loop, the program writes out the value of count, and then increases it by 1. It does this 10 times, as follows.

First of all, the assignment in the first part of the for statement (count = 1) is executed, thus initialising the counter.

Then the condition in the second part of the for loop (count <= 10) is tested.

If it evaluates to true,

the statement in the body of the loop (which displays the value of count) is executed,

the assignment statement in the third part of the for statement (count = count + 1) is executed,

the condition is tested again (and so on).

If it evaluates to false,

the body of the loop is skipped and control passes to the statement following the loop (which in this case is the statement to output Thank you).

(b) The final value of count is 11.
Note that this is one more than the 'final' value specified in the condition, because it is only when count reaches 11 that the condition in the for statement evaluates to false.

In the examples that follow, we sometimes refer to the 'final' value assigned to the counter variable in the loop control statement. In this context we are talking about the final value for which the loop body is executed, not its value once all the required iterations have taken place.

## Activity 2

We have provided for_activity_2.html so that you can experiment with using different initial, final and step values for a for loop. The program will repeatedly prompt you for these three values and then execute a for loop similar to the one in the first activity until you decide to stop. Here is the section of the program that prompts you for your inputs and executes a for loop. The variables initialValue, endValue and stepValue will have been declared earlier in the program.

initialValue = window.prompt('Please enter an initial value for count','');
initialValue = parseFloat(initialValue);
endValue = window.prompt('Please enter a stopping value for count','');
endValue = parseFloat(endValue);
stepValue = window.prompt('Please enter a step value','');
stepValue = parseFloat(stepValue);
for (var count = initialValue; count <= endValue; count = count + stepValue)
{
document.write('Count is ' + count + '<BR>');
}
document.write('Thank you'+ '<BR>');

You do not need to understand the complete program at this stage, but if you are interested you can look at the file by opening it up in your text editor. You will see that it works by nesting the for loop 'inside' the while loop, i.e. the for loop is one of the statements in the body of the while loop.

(a) Run the program with a step value of 1 and various different inputs for the initial and stopping values, and study the output.

(b) What happens when the initial value you enter is greater than the stop value?

(c) Run the program again with a step value of 2 and various different inputs for the initial and stop values. How many times is the body of the loop executed for the following pairs of initial and stopping values?

3, 10
4, 10
3
, 11
4
, 11

(a) The output showing the value of count is similar to that from the last activity, but the values of count displayed will start from whatever you entered as the initial value, and end with your stopping value.

(b) If you enter an initial value which is greater than the final value, then the condition will evaluate to false the first time it is tested, so the body of the loop will never be evaluated and the value of count will never be displayed.

(c) This demonstrates that loop counters needn't necessarily be incremented in steps of 1; count starts at the initial value and then goes up in steps of 2. The condition evaluates to false when the value of count reaches its greatest possible value which is less than or equal to the stopping value.

For initial and stopping values of 3 and 10 the loop will be executed four times (with count taking the values 3, 5, 7, 9)
For initial and stopping values of 4 and 10 the loop will be executed four times (with count taking the values 4, 6, 8, 10)
For initial and stopping values of 3 and 11 the loop will be executed five times (with count taking the values 3, 5, 7, 9, 11)
For initial and stopping values of 4 and 11 the loop will be executed four times (with count taking the values 4, 6, 8, 10)

## Activity 3

for_activity_3.html is the same as the one in activity 2 except that the lines:

for (var count = initialValue; count <= endValue; count = count + stepValue)

have been replaced by the lines:

for (var count = initialValue; count >= endValue; count = count - stepValue)

(the comparison operator has been changed from <= to >= and the counter is decremented rather than incremented).

Run the program with a variety of initial, stopping and step values.

(a) How many times is the body of the for loop executed with initial and stopping values of 2 and 5, and a step value of 1?

(b) How many times is the body of the for loop executed with initial and stopping values of 10 and 1, and a step value of 1?

This activity demonstrates that for loops can be written with decreasing as well as increasing counters.

(a) In this case (a descending count with an initial value less than the final value) the condition in the for loop will evaluate to false the first time it is tested, so the body of the for loop will not be executed at all.

(b) The loop body will be executed 10 times.

Next we'll be looking at the Syntax of a for Loop, and you'll be experimenting further with some other ways of using loops.