Database development and training for Birmingham and the midlands
Specialists in Microsoft Access and Visual Foxpro database training and development
I am happy to hear from existing clients but I am taking no new calls.
There are situations where you need the program to repeat the same commands for a known number of times. If there were only two or three repetions of a single command then you might just type that command out two or three times but a for gives you more flexibility and saves you a lot of typing:
This syntax looks to be terse and inpenetrable if you're used to the FoxPro and Basic family of languages with their English-like for...step...next syntax but the statement is not as bad as it looks.
The loop controls a single statement, in this case it's just a write statement. The expressions inside the parentheses following the for on the first line define how many times this statement is to run. There are three parts to this control statement:
var i = 0;
The loop is to be controlled by a variable named "i" and that variable is going to start with a value of zero.
i < 10;
The loop will run whilst this statement is true. The statements inside the body of the loop will execute whilst i remains less than 10.
i = i + 1
Blocks of statements
As with the if, statement, the for loop can only control a single statement and we use the same technique of wrapping a block of statements in braces if we do need more than one primitive statement in the body of the loop. Our first program listed all the values of i on the same line without spaces so let's add some HTML formatting and put each number into its own paragraph:
Other for loops
Most for loops go up in steps of 1 but you don't have to change the loop counter by 1 and you don't have to increase it. You can count down instead:
This script counts down from 10 in steps of 2. The obvious differenece is that the increment has been changed to suit but notice the other changes as well. We've had to change the initial value of i and change the condition that ends the loop.