Back to course

Looping Structures: The 'for' loop

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 19: Looping Structures: The for Loop

The for loop is ideal when the number of iterations is known beforehand or when you need a clear structure for initialization, condition checking, and updating.

for Loop Syntax

c for (initialization; condition; increment/decrement) { // Code block to execute }

The Three Expressions

  1. Initialization: Executed only once at the start of the loop (e.g., int i = 0;).
  2. Condition: Checked before every iteration. If True, the loop continues.
  3. Increment/Decrement (Update): Executed after the loop body runs, typically used to progress the loop control variable.

Example: Iterating 0 to 9

c #include <stdio.h>

int main() { int i; // i starts at 0, runs while i < 10, i increases by 1 each time for (i = 0; i < 10; i++) { printf("i is: %d\n", i); } return 0; }

Nested Loops

You can place one loop inside another. This is commonly used for iterating over 2D data structures (like tables or matrices).

c // Example: Printing a 3x3 grid for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { printf("(%d, %d) ", row, col); } printf("\n"); // Move to the next line after finishing a row }