For loop Code
I want to execute the same set of statements numerous time based on a incremental or decremental value?
As we state it, for loop is a looping syntax.
// set of statements that will be executed
As defined in the syntax, for loop takes three parameters, the initial value (e.g i=0), condition - the statements inside "for" will be executed until this condition is satisfied (e.g i<7), increment - this is where we set the initial value to be increased or decreased after each loop.
All the three parameters are separated by semicolon ";".
For an example, we will consider a situation where we want to add all numbers between one and ten.
var i=0; var total=0;
for(i=1; i<11; i++)
total = total+i;
document.write("--------- The total ------: "+total);
The example worked as follows,
a) Initially we created the for loop by setting variable i as 1.
b) then we set the condition that the loop should execute till i is less than 11 (i<11).
c) We made the variable to be incremented at the end of each loop (i++)
First loop: i=0, i<11 is true so the statement executed, now total becomes 0+1 =1 and i incremented to 2.
Second loop: now i=1, i<11 is true so the statement executed, now total becomes 1+2 =3 and i incremented to 2.
this continues till i=11
Last loop: now i=11, i<11 becomes false and the loop ends here.Note: i++ increments the value at the end on the loop, while ++i to increase the value of i at the start of the loop.