The for
loop repeats a sequence of instructions like the
while and do..while loops.
The for
loop is particularly suitable for loops that need to run a given
number of times. Typically, to count or to browse indexed data (such as arrays for example):
for ( i=0 ; i<100 ; i++) {
//...
}
The for
loop expects 3 parameters:
for ( initialization ; test ; iterator ) {
// ...
Block of instructions
// ...
}
As with the while and do..while
the for
loop repeats the sequence of instructions as long as the condition is true.
Here is the flowchart for the for
loop:
Note the arrangement of the blocks in the flowchart. The configuration is similar to the while loop. The body of the loop may not be executed if the test is false from the start.
for
, unless the instruction block is empty.Each parameter is optional, we can write for(;;);
, which is equivalent to while(1);
.
Here is an example of a for
loop that displays all integers between 0 and 42:
int i;
// Display integers between 0 and 42
for ( i=0 ; i<=42 ; i++) {
printf ("%d ", i);
}
Here is an example of a for
loop that displays the integers between -27 and 15 with a step of 3 :
int i;
// Displays the integers between -27 and 15 with a step of 3
for ( i=-27 ; i<=15 ; i+=3) {
printf ("%d ", i);
}
Write a program that displays all integers between 0 and 49 inclusive:
int i;
// Display integers from 0 to 49
// COMPLETE HERE
Write a program that displays all integers in descending order from 49 to 0 inclusive:
int i;
// Displays all integers in descending order from 49 to 0 inclusive:
// COMPLETE HERE
Write a program that displays all integers from 0 to 256 with a step of 16 :
int i;
// Displays all integers from 0 to 256 with a step of 16
// COMPLETE HERE
Write a program that displays all powers of 2 from 1 to 1024 :
int i;
// Displays all powers of 2 from 1 to 1024
// COMPLETE HERE
Here is the expected output:
1 2 4 8 16 32 64 128 256 512 1024
Write the code that displays a square with n letters on each side containing the letters of the alphabet.
A
.B
C
.Here is an example for a square of size 6x6:
ABCDEF
BCDEFG
CDEFGH
DEFGHI
EFGHIJ
FGHIJK
What does the following code display?
for ( i=0 ; i<5 ; i++)
printf ("%d ",i);
i
is 5, we leave the loop before the display.
Try again...
What does the following code display?
for ( i=0 ; i<=5 ; i++)
printf ("%d ",i);
i
is 5, there is a last iteration, because the test is less than or equal..
Try again...
What does the following code display?
for ( i=5 ; i>=0 ; i--)
printf ("%d ",i);
What does the following code display?
for ( i=5 ; i>0 ; i--);
printf ("%d ",i);
for
, the program displays 0.
Try again...
What does the following code display?
int i,j;
for ( i=0 ; i<4 ; i++)
for ( j=0 ; j<3 ; j++)
printf ("%d ", j);
What does the following code display?
int i,j;
for ( i=0 ; i<4 ; i++) {
for ( j=0 ; j<i ; j++)
printf ("%d ", j);
printf ("- ");
}
i
is 0, we do not enter the second loop.
Try again...