A for loop is a convenient abbreviation for a while loop that is useful for special purposes, such as counting, or other very simple loops.
Advantage. Normally, a loop needs some initialization, a condition that tells when to keep looping, and some update code to update the values of some variables. It is easy to forget one or more of those parts. A for loop has a place for each one, so that you are less likely to forget them.
A for loop has the form
for(init; cond; update) { body }where init is the initialization, cond is the condition to do another iteration of the loop, and update does the update. This loop has the same meaning as
init while(cond) { body update }
There are three parts of the for loop heading, and they are separated by semicolons.
The parentheses around the three parts are required.
The initialization part comes first, and it is only done once, at the beginning.
Since the condition is tested at the beginning of the loop, the loop body is done zero or more times.
The following prints the numbers from 1 to 20, one per line.
int k; for(k = 1; k <= 20; k++) { System.out.println(k); }
The following makes variable sum hold 1 + 2 + ... + n, where n is a variable that has already been given a value earlier.
int k, sum; sum = 0; for(k = 0; k <= n; k++) { sum = sum + k; }
Questions.
Suppose that you use the following to compute the sum 1 + 2 + ... + n. Does it work for every nonnegative integer value of n? If not, give a counterexample.
int k, sum; sum = 0; for(k = 1; k <= n; k++) { sum = sum + k; }Answer[25]
What is wrong with the following?
int i; for(i = 0, i <= 10, i++) { s += i; }Answer[26]
What is wrong with the following?
int j; for(j <= 10) { s += i; j++; }Answer[27]