← The C Language
Lesson 18 of 77 · 10 XP
The for loop
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
for puts the three parts of a counting loop on one line:
for (int i = 0; i < 5; i++) {
printf("%d ", i); // 0 1 2 3 4
}
int i = 0— runs once at the start;i < 5— checked before each step;i++— runs after each step.
Any part can be left out: for (;;) is an endless loop.
Loops can be nested inside each other:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= row; col++)
printf("*");
printf("\n");
}
// *
// **
// ***
A variable declared in a for lives only inside the loop (since C99).
Task. Read n and print a "staircase" of n lines: line k contains the numbers from 1 to k, separated by spaces.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.