C - For Loop

The for loop is compact and ideal when the iteration count is known.

Learning Objectives

  • Write for loops with init, condition, and update expressions.

Prerequisites

Example

#include <stdio.h>

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

Common Pitfalls

  • Off-by-one errors in bounds.

Checks for Understanding

  1. How many times does the loop run for i = 0; i < 5; i++?
Show answers
  1. Five times (i = 0,1,2,3,4).