Back to Blog

C in 100 Seconds: For Loops | Episode 8

Daryl WongDaryl Wong

Video: C in 100 Seconds: For Loops — Init Condition Step | Episode 8 by Taught by Celeste AI - AI Coding Coach

Watch full page →

For Loops — Compact Iteration in C

C in 100 Seconds, Episode 8


The for loop packs initialization, condition, and update into a single line. When you know how many times to loop, for is the right tool.

The For Loop

for (int i = 1; i <= 5; i++) {
  printf("%d ", i);
}

Output: 1 2 3 4 5

Three parts separated by semicolons:
1. Initint i = 1 runs once before the loop starts
2. Conditioni <= 5 is checked before each iteration
3. Updatei++ runs after each iteration

Nested Loops

Put one loop inside another to work with grids, tables, or any two-dimensional pattern:

for (int row = 1; row <= 3; row++) {
  for (int col = 1; col <= 3; col++) {
    printf("(%d,%d) ", row, col);
  }
  printf("\n");
}

Output:

(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

The outer loop controls rows; the inner loop controls columns. For each row, the inner loop runs to completion before the outer loop advances.

For vs While

A for loop is really just a while loop with the init and update built in. Use for when you have a clear counter. Use while when the loop depends on a condition that changes unpredictably.

Full Code

#include <stdio.h>

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

  for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
      printf("(%d,%d) ", row, col);
    }
    printf("\n");
  }

  return 0;
}

Compile and Run

gcc forloop.c -o forloop
./forloop

Next episode: Functions — breaking your code into reusable pieces.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode08