Utilizor
Contact Us
HomeC TutorialC For Loop

CC For Loop

Looping a specific number of times.

C For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
  • Statement 1 is executed (one time) before the execution of the code block.
  • Statement 2 defines the condition for executing the code block.
  • Statement 3 is executed (every time) after the code block has been executed.

Examples

For Loop

c example

Loops from 0 to 4.

#include <stdio.h>

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

Nested Loops

c example

Loop inside a loop.

#include <stdio.h>

int main() {
  int i, j;
  
  // Outer loop
  for (i = 1; i <= 2; ++i) {
    printf("Outer: %d\n", i);  // Executes 2 times
    
    // Inner loop
    for (j = 1; j <= 3; ++j) {
      printf(" Inner: %d\n", j);  // Executes 6 times (2 * 3)
    }
  }
  
  return 0;
}

Test Your Knowledge

1. In a 'for' loop, which statement is executed only once?

2. Which loop is best when you know the number of iterations?