For Loop

In all C-like programming languages, the for construct is composed of three parts, each divided by a semicolon:

for(initialization; test; update) { ... }

  • In the first section, the initialization, we initialize an index variable (which is usually being named i, j or k) to its initial value;
  • In the second part, we test whether a variable satisfies a certain condition: if it does, we enter the loop one more time, otherwise we exit from it;
  • In the third and last part, we update the variable — usually by incrementing or decrementing it by 1.

How the For Loop Works


for(i = 0; i < 10; i++) { printf("%d ", i); }
The variable i is initialized to 0;

  • The test "i < 10" is performed, and the code enclosed in curly brackets is executed if the test is successful, exiting the loop otherwise;
  • The index i is incremented (i++);
  • The points 2-3 are repeated until the test "i < 10" fails and we exit the loop.

Output: 0 1 2 3 4 5 6 7 8 9

Notice that the number 10 is not being printed, because i is first incremented from 9 to 10, and then tested. When we exit the loop, we do so because the condition i < 10 is no more true, since i is now equal to 10.