If A, B and C are expressions then
for(A; B; C) { body }is equivalent to
{ A; while(B) { body C; } }For example,
for(i = 0; i < 5; i++)
{
printf"%d\n", i);
}
is the same as
{
i = 0;
while(i < 5)
{
printf("%d\n", i);
i++;
}
}
An advantage of a for-loop is that the initialization, update and test
of one of the control variables are all together in one place, so it
is easier to see what the loop is doing and it is more difficult to make
a mistake.
Declaring a variable in a for-loop heading
The first part of a for-loop heading can create a new variable. But
a variable created there can only be used in the for-loop heading and
body. For example
for(int i = 0; i < 5; i++) { printf("%d\n", i); }creates variable i that can only be used in this for-loop. You are not allowed to say for(int i = 0; i < 5; i++) { printf("%d\n", i); } printf("%d\n", i);since that tries to use i outside of the for-loop. |
Omitting part of a for-loop heading
Every for-loop heading has exactly two semicolons. But you
can omit any (or all) of the three parts that are separated
by semicolons. If the first part is empty, no initialization
is done. If the second part is empty, it is assumed to be
true, so the loop keeps going until stopped some other way.
If the third part is empty, no update is added to the end
of the body. For example,
for(; k < n; k++) { ... }assumes that k has already been initialized. Only omit parts of the heading with good reason. For example, int k = 0; for(; k < n; k++) { ... }does not make sensible use of the for-loop. If there is initialization to be done, do it in the heading, as in int k; for(k = 0; k < n; k++) { ... } |
Watch out: semicolons
Be careful not to end the heading of a for-loop with a semicolon.
for(int n = 0; n < 4; n++); { printf("%i\n", n); n++; }writes 4because the body of the for-loop is an empty statement. |
Solve question 1 from the page on while loops, but this time use a for-loop. Answer
Solve question 2 from the page on while loops, but this time use a for-loop. Answer
Solve question 3 from the page on while loops, but this time use a for-loop. Answer