🎓 A1Learner
🔍
0 of 50 lessons completed

C For Loop

A for loop repeats a block a set number of times. While and do while repeat until a check fails; a for loop packs the start, the check, and the step into one line.

Count from 0 to 2

i takes the values 0, 1, then 2. The check fails at 3, so the loop prints 0, 1, 2.

#include <stdio.h>

int main() {
  for (int i = 0; i < 3; i++) {
    printf("%d\n", i);
  }
  return 0;
}

Count from 1 to 5

n starts at 1 and stops when it passes 5. The print lines show 1 through 5.

#include <stdio.h>

int main() {
  for (int n = 1; n < 6; n++) {
    printf("%d\n", n);
  }
  return 0;
}

Add numbers in a loop

Total grows by 1, then 2, then 3, then 4, then 5. The print line shows 15.

#include <stdio.h>

int main() {
  int total = 0;
  for (int n = 1; n < 6; n++) {
    total = total + n;
  }
  printf("%d\n", total);
  return 0;
}

Example

#include <stdio.h>

int main() {
  for (int i = 5; i > 0; i--) {
    printf("%d\n", i);
  }
  printf("Go!\n");
  return 0;
}

Key points

  • A for loop starts with the word for and three parts in round brackets.
  • The first part sets up the loop variable, like int i = 0;.
  • The second part is the check, and the loop runs while the check is true.
  • The third part runs after each round, and it often adds 1 to the loop variable.
  • The three parts are split by semicolons.
  • The loop variable counts the rounds, and it often starts at 0.
  • A for loop suits a count you know before the loop starts.

The loop counts down from 5, printing each value as i falls. Once i reaches 0, the check fails and Go! prints.

Note

A for loop with i < 3 runs for i = 0, 1, and 2, so it runs 3 times.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How many times does for (int i = 0; i < 5; i++) run its block?