C

C Fundamentals

18 lessons

Progress0%
1. Introduction to C
1What is C?
2. Variables and Data Types
1Data Types in C
3. Control Flow
ConditionalsLoops
4. Functions
Defining FunctionsRecursion
5. Arrays and Pointers
Arrays and StringsPointers
6. Memory Management
Dynamic MemoryStructs and Files
7. Preprocessor & Macros
Preprocessor DirectivesMacros & Inline Functions
8. Bitwise Operations
Bitwise OperatorsBit Flags & Masking
9. Enums, Unions & typedef
Enums & typedefUnions & Complex Types
10. Multi-file Programs
Header Files & Compilation UnitsLinkage, Storage Classes & Make
All Tutorials
CControl Flow
Lesson 4 of 18 min
Chapter 3 · Lesson 2

Loops

Loops in C

C provides three loop constructs.

for loop All three parts (init; condition; update) are optional:

c
for (int i = 0; i < n; i++) { … }

while loop Condition tested before the body:

c
while (condition) { … }

do-while loop Body executes at least once:

c
do { … } while (condition);

Nested loops Common for multi-dimensional iteration. Outer loop rows, inner loop columns.

break and continue

  • break exits the innermost loop (or switch).
  • continue skips to the next iteration of the innermost loop.

Key points:

  • Omitting the for-loop condition creates an infinite loop: for (;;) { }.
  • Loop variables declared inside for (int i = …) require C99 or later.
  • Be careful of off-by-one errors: i < n vs i <= n.

Code Examples

for, while, do-whilec
#include <stdio.h>

int main(void) {
    // for loop — sum 1 to 5
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }
    printf("Sum: %d\n", sum);

    // while — find smallest power of 2 >= 50
    int n = 1;
    while (n < 50) n *= 2;
    printf("Power of 2 >= 50: %d\n", n);

    // do-while
    int x = 1;
    do {
        printf("%d ", x);
        x *= 2;
    } while (x <= 16);
    printf("\n");
    return 0;
}

do-while always runs the body once. The while loop condition is checked before each iteration.

Nested loops and break/continuec
#include <stdio.h>

int main(void) {
    // Multiplication table (3x3)
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            printf("%2d ", i * j);
        }
        printf("\n");
    }

    // continue: skip even numbers
    printf("Odd 1-10: ");
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Nested loops iterate over a 2D grid. continue skips even numbers — execution jumps to i++ and the next iteration.

Quick Quiz

1. What does `for (;;) { }` represent in C?

2. Which loop guarantees at least one execution of the body?

Was this lesson helpful?

PreviousNext