loops in C for while do while guide Python comparison IC2

Loops in C — for, while and do…while without detours

Loops in C for, while and do...while work with exactly the same logic as Python — the concept of repeating a block of code is identical. What changes is the syntax and one important addition: the do...while loop that Python doesn’t have. If you understood loops in Python, you’re 80% of the way there.

This article covers the remaining 20% — the C-specific syntax, the differences that matter and the mistakes that cost the most time in IC2.

The for loop in C

In Python for always iterates over a sequence — a list, a range, a string. In C for is a numeric control loop with three explicit parts separated by semicolons:

# Python
for i in range(5):
    print(i)
// C
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

The three parts inside the parentheses:

int i = 0 — initialisation. Runs once before the loop starts. Declares and initialises the counter variable.

i < 5 — condition. Checked before each iteration. If true, the body runs. If false, the loop ends.

i++ — update. Runs after each iteration. Advances the counter.

The execution flow:

1. int i = 0           → initialisation (once only)
2. i < 5?  → true     → execute body
3. i++                 → i is now 1
4. i < 5?  → true     → execute body
5. i++                 → i is now 2
...
6. i++                 → i is now 5
7. i < 5?  → false    → loop ends

Python range() equivalents in C

# range(n)
for i in range(5):         # 0, 1, 2, 3, 4
for (int i = 0; i < 5; i++) {
# range(start, end)
for i in range(2, 7):      # 2, 3, 4, 5, 6
for (int i = 2; i < 7; i++) {
# range(start, end, step)
for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
for (int i = 0; i < 10; i += 2) {
# reversed range
for i in range(5, 0, -1):  # 5, 4, 3, 2, 1
for (int i = 5; i > 0; i--) {

The increment operators — i++, i–, i+=n

C has increment and decrement operators that don’t exist in Python:

i++    // i = i + 1 (post-increment)
i--    // i = i - 1 (post-decrement)
++i    // i = i + 1 (pre-increment)
--i    // i = i - 1 (pre-decrement)
i += 2 // i = i + 2
i -= 3 // i = i - 3
i *= 2 // i = i * 2
i /= 4 // i = i / 4
i %= 3 // i = i % 3

In a for loop i++ and ++i are equivalent — the difference matters only inside expressions, which is rare in loops. Use i++ by convention.

Variable scope in the for loop

A variable declared inside the for only exists within that loop:

for (int i = 0; i < 5; i++) {
    printf("%d\n", i);    // i exists here
}
printf("%d\n", i);        // compile error — i doesn't exist here

If you need the variable after the loop, declare it before:

int i;
for (i = 0; i < 5; i++) {
    printf("%d\n", i);
}
printf("Final value: %d\n", i);    // → 5

The while loop in C

Identical concept to Python — evaluates the condition before each iteration:

# Python
counter = 0
while counter < 5:
    print(counter)
    counter += 1
// C
int counter = 0;
while (counter < 5) {
    printf("%d\n", counter);
    counter++;
}

The most important rule with while: always update the condition variable inside the loop. Forgetting it creates an infinite loop:

// INFINITE LOOP — counter never changes
int counter = 0;
while (counter < 5) {
    printf("%d\n", counter);
    // missing counter++ → loops forever
}

If this happens press Ctrl + C in the terminal to force-quit the program.

The do…while loop — exclusive to C (and Java)

do...while doesn’t exist in Python. It’s like while but the condition is evaluated at the end — guaranteeing the body executes at least once:

// while — may never execute if condition starts false
while (condition) {
    // might never run
}

// do...while — always runs at least once
do {
    // always runs at least once
} while (condition);    /* semicolon required here */

The classic use case — input validation:

int option;
do {
    printf("Menu:\n");
    printf("1. Option A\n");
    printf("2. Option B\n");
    printf("3. Exit\n");
    printf("Choose (1-3): ");
    scanf("%d", &option);

    if (option < 1 || option > 3) {
        printf("Invalid option — try again\n\n");
    }
} while (option < 1 || option > 3);    /* repeats while invalid */

printf("You chose: %d\n", option);

If you used while instead you’d need to initialise option to an invalid value before the loop to force entry — do...while avoids that artificial initialisation.

when to use for, while or do…while

for       → know how many iterations in advance
            counters, tables, arrays, ranges

while     → don't know how many — depends on a condition
            search, reading until sentinel value, games

do...while → always need at least one iteration
             menu display, input validation

break and continue in C

break and continue work identically to Python:

// break — exit loop immediately
for (int i = 0; i < 10; i++) {
    if (i == 5) break;       // stops at 5
    printf("%d ", i);
}
// → 0 1 2 3 4

// continue — skip to next iteration
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue; // skip even numbers
    printf("%d ", i);
}
// → 1 3 5 7 9

break in nested loops only exits the innermost loop — to exit both you need a flag:

int found = 0;

for (int i = 0; i < 10 && !found; i++) {
    for (int j = 0; j < 10 && !found; j++) {
        if (i * j == 42) {
            printf("Found: i=%d, j=%d\n", i, j);
            found = 1;
        }
    }
}

Nested loops — a loop inside another

// Multiplication table 1 to 3
for (int i = 1; i <= 3; i++) {          // outer: rows
    for (int j = 1; j <= 10; j++) {     // inner: columns
        printf("%3d", i * j);
    }
    printf("\n");    // newline after each row
}

Output:

  1  2  3  4  5  6  7  8  9 10
  2  4  6  8 10 12 14 16 18 20
  3  6  9 12 15 18 21 24 27 30

For each value of i the inner loop runs completely through all values of j. Total iterations: 3 × 10 = 30.

The accumulator pattern in C

// Sum and average of 5 grades
double grades[5];
double sum = 0;

for (int i = 0; i < 5; i++) {
    printf("Grade %d: ", i + 1);
    scanf("%lf", &grades[i]);
    sum += grades[i];
}

double average = sum / 5.0;    // 5.0 not 5 — avoid integer division
printf("Average: %.2f\n", average);

Golden rule: initialise the accumulator to 0 before the loop, update inside, use after.

A complete program — all three loops

#include <stdio.h>

int main() {
    /* FOR — multiplication table */
    printf("=== Multiplication Table ===\n");
    int n;
    printf("Number: ");
    scanf("%d", &n);

    for (int i = 1; i <= 10; i++) {
        printf("%d x %2d = %3d\n", n, i, n * i);
    }

    /* WHILE — countdown */
    printf("\n=== Countdown ===\n");
    int start;
    printf("Start from: ");
    scanf("%d", &start);

    while (start > 0) {
        printf("%d... ", start);
        start--;
    }
    printf("GO!\n");

    /* DO...WHILE — validated menu */
    printf("\n=== Menu ===\n");
    int option;
    do {
        printf("1. Hello  2. Goodbye  3. Exit\n");
        printf("Option: ");
        scanf("%d", &option);

        switch (option) {
            case 1: printf("Hello!\n"); break;
            case 2: printf("Goodbye!\n"); break;
            case 3: printf("Exiting...\n"); break;
            default: printf("Invalid option\n");
        }
    } while (option != 3);

    return 0;
}

Compile and run:

gcc loops_demo.c -o loops_demo -Wall
./loops_demo

Visualise with Python Tutor

Select C from the dropdown and paste in pythontutor.com:

#include <stdio.h>
int main() {
    /* for */
    for (int i = 0; i < 3; i++) {
        printf("for: %d\n", i);
    }

    /* while */
    int j = 3;
    while (j > 0) {
        printf("while: %d\n", j);
        j--;
    }

    /* do...while */
    int k = 0;
    do {
        printf("do...while: %d\n", k);
        k++;
    } while (k < 3);

    return 0;
}

Step through all three loops and compare them. Watch how for manages the counter automatically in its three parts — init, check, increment — all in one line. while requires you to manage the counter manually before and inside the loop. do...while always prints at least once even if the condition starts false — try changing k = 0 to k = 5 and watch it still execute once before checking k < 3.

Quick summary

/* FOR — known iterations */
for (int i = 0; i < n; i++) { }       /* 0 to n-1 */
for (int i = 1; i <= n; i++) { }      /* 1 to n */
for (int i = n; i > 0; i--) { }       /* n down to 1 */
for (int i = 0; i < n; i += 2) { }   /* step 2 */

/* RANGE EQUIVALENTS */
/* range(n)      → for (int i = 0; i < n; i++) */
/* range(a,b)    → for (int i = a; i < b; i++) */
/* range(a,b,s)  → for (int i = a; i < b; i += s) */

/* INCREMENT OPERATORS */
i++   i--   ++i   --i
i += n   i -= n   i *= n   i /= n   i %= n

/* WHILE — condition-based */
while (condition) {
    /* code */
    /* ALWAYS update the condition variable */
}

/* DO...WHILE — at least one execution */
do {
    /* always runs at least once */
} while (condition);    /* semicolon required */

/* WHEN TO USE EACH */
/* for        → know how many: counters, arrays, tables */
/* while      → don't know: search, sentinel value */
/* do...while → need at least one run: menus, validation */

/* BREAK AND CONTINUE */
break;      /* exit loop immediately */
continue;   /* skip to next iteration */

/* NESTED LOOPS */
for (int i = ...) {
    for (int j = ...) {     /* use different variable names */
        ...
    }
}
/* break only exits innermost loop */
/* use flag variable to exit multiple levels */

/* ACCUMULATOR PATTERN */
double sum = 0;                         /* 1. init BEFORE */
for (int i = 0; i < n; i++) {
    sum += values[i];                   /* 2. update INSIDE */
}
double avg = sum / (double)n;           /* 3. use AFTER */

/* INFINITE LOOP — press Ctrl+C to stop */
while (1) { }     /* deliberate infinite loop */
/* accidental: forgot to update condition variable */

/* COMMON ERRORS */
/* 1. Missing { } with multiple statements in body */
/* 2. Forgetting to update while condition → infinite loop */
/* 3. Off-by-one: range(n) = 0 to n-1, use i < n not i <= n */
/* 4. Integer division inside loop: sum/n not sum/(double)n */
/* 5. Missing semicolon after do...while condition */

In the next article we practice C loops with three real programs in Fedora.

Similar Posts

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *