For Loops

From Q
Jump to navigation Jump to search

For loops can be used to repeatedly execute some code. In the following example, a variable called x is created and the number 1 is added to it 10 times.

var x = 0;// creating a new variable, with an initial value of 0
for (var i = 0; i <10; i++)
  x = x + 1;

The next example, does exactly the same thing as the the previous example, except that the number of loops (i.e., iterations) is itself set in a different variable.

var n_iterations = 10;
var x = 0;
for (var i = 0; i <n_iterations ; i++)
  x = x + 1;

This does exactly the same thing as the previous example, except that 1 is added in a slightly more efficient way:

var n_iterations = 10;
var x = 0;
for (var i = 0; i <n_iterations ; i++)
  x += 1;

This does exactly the same thing as the previous example, except that 1 is added automatically each time by using ++.

var n_iterations = 10;
var x = 0;
for (var i = 0; i <n_iterations ; i++)
  x++;

When we wish to execute multiple lines of code within each branch, this is done using parentheses. In this example, 1 is added to x and then it is doubled and this occurs 10 times.

var n_iterations = 10;
var x = 0;
for (var i = 0; i <n_iterations ; i++){
  x++;
  x *= 2;
}


See also