Docs

README

Loops in C (for, while, do-while)

📖 Introduction

Loops allow you to execute a block of code repeatedly. C provides three types of loops: for, while, and do-while. Each has its use case depending on when you know how many iterations you need and when the loop condition should be checked.


🎯 Types of Loops

                       C Loops
                          │
        ┌─────────────────┼─────────────────┐
        │                 │                 │
      for             while            do-while
        │                 │                 │
   ┌────┴────┐      ┌─────┴─────┐     ┌─────┴─────┐
   │ Counter │      │ Pre-test  │     │ Post-test │
   │ based   │      │ loop      │     │ loop      │
   │ Known   │      │ Unknown   │     │ Execute   │
   │ count   │      │ count     │     │ at least  │
   └─────────┘      └───────────┘     │ once      │
                                      └───────────┘

📝 The for Loop

The for loop is best when you know the number of iterations beforehand.

Syntax:

for (initialization; condition; update) {
    // loop body
}

Components:

PartDescriptionExample
InitializationExecuted once at startint i = 0
ConditionChecked before each iterationi < 10
UpdateExecuted after each iterationi++
BodyCode to repeatprintf("%d", i);

Flowchart:

       ┌─────────────────┐
       │ Initialization  │
       │    (i = 0)      │
       └────────┬────────┘
                │
                ▼
       ┌─────────────────┐
   ┌──►│ Condition true? │
   │   │    (i < 10)     │
   │   └────────┬────────┘
   │            │
   │     Yes    │    No
   │            ▼            ▼
   │   ┌─────────────────┐   Exit
   │   │ Execute body    │   loop
   │   └────────┬────────┘
   │            │
   │            ▼
   │   ┌─────────────────┐
   │   │ Update (i++)    │
   │   └────────┬────────┘
   │            │
   └────────────┘

Examples:

// Count from 1 to 5
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
// Output: 1 2 3 4 5

// Count down from 5 to 1
for (int i = 5; i >= 1; i--) {
    printf("%d ", i);
}
// Output: 5 4 3 2 1

// Step by 2
for (int i = 0; i <= 10; i += 2) {
    printf("%d ", i);
}
// Output: 0 2 4 6 8 10

// Iterate through array
int arr[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
}

📋 The while Loop

The while loop is best when you don't know how many iterations you need.

Syntax:

while (condition) {
    // loop body
}

Flowchart:

          ┌────────────────┐
      ┌──►│ Condition true?│
      │   └───────┬────────┘
      │           │
      │    Yes    │    No
      │           ▼            ▼
      │   ┌────────────────┐   Exit
      │   │ Execute body   │   loop
      │   └───────┬────────┘
      │           │
      └───────────┘

Examples:

// Print numbers 1 to 5
int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}

// Wait for user input
char input;
while (input != 'q') {
    printf("Enter command (q to quit): ");
    scanf(" %c", &input);
}

// Sum until condition
int sum = 0, num = 1;
while (sum < 100) {
    sum += num;
    num++;
}
printf("Sum = %d\n", sum);

🔄 The do-while Loop

The do-while loop guarantees at least one execution of the loop body.

Syntax:

do {
    // loop body
} while (condition);  // Note the semicolon!

Flowchart:

       ┌─────────────────┐
       │ Execute body    │◄──┐
       └────────┬────────┘   │
                │            │
                ▼            │
       ┌─────────────────┐   │
       │ Condition true? │   │
       └────────┬────────┘   │
                │            │
         Yes    │    No      │
                └───►────────┘
                     │
                     ▼
                   Exit
                   loop

Examples:

// Menu that runs at least once
int choice;
do {
    printf("\n1. Option A\n");
    printf("2. Option B\n");
    printf("3. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);
} while (choice != 3);

// Input validation
int age;
do {
    printf("Enter age (0-120): ");
    scanf("%d", &age);
} while (age < 0 || age > 120);

// Number guessing game
int guess, secret = 42;
do {
    printf("Guess the number: ");
    scanf("%d", &guess);
} while (guess != secret);
printf("Correct!\n");

⚖️ Comparison of Loops

Featureforwhiledo-while
Condition checkBefore bodyBefore bodyAfter body
Min executions001
Best forKnown countUnknown countMust run once
InitializationIn headerBefore loopBefore loop
UpdateIn headerIn bodyIn body

When to Use:

Need known number of iterations?
    │
    ├── Yes ──► Use FOR loop
    │
    └── No ──► Need at least one execution?
                    │
                    ├── Yes ──► Use DO-WHILE loop
                    │
                    └── No ──► Use WHILE loop

🔢 Loop Control Variables

Multiple Variables in for:

// Two variables
for (int i = 0, j = 10; i < j; i++, j--) {
    printf("i=%d, j=%d\n", i, j);
}

// Different types (not recommended but possible)
for (int i = 0, j = 5; i < j; i++) {
    // ...
}

Variable Scope:

// i is only visible inside the loop (C99+)
for (int i = 0; i < 10; i++) {
    printf("%d ", i);
}
// printf("%d", i);  // ERROR: i not in scope

// If you need i after loop, declare outside
int i;
for (i = 0; i < 10; i++) {
    // ...
}
printf("Final i = %d\n", i);  // OK: i = 10

🎯 Common Loop Patterns

Pattern 1: Counting

// Count up
for (int i = 0; i < n; i++) { }

// Count down
for (int i = n - 1; i >= 0; i--) { }

// Count by step
for (int i = 0; i < n; i += step) { }

Pattern 2: Array Traversal

int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

// Forward
for (int i = 0; i < size; i++) {
    printf("%d ", arr[i]);
}

// Backward
for (int i = size - 1; i >= 0; i--) {
    printf("%d ", arr[i]);
}

Pattern 3: String Processing

char str[] = "Hello";

// Until null terminator
for (int i = 0; str[i] != '\0'; i++) {
    printf("%c ", str[i]);
}

// Using pointer
for (char *p = str; *p != '\0'; p++) {
    printf("%c ", *p);
}

Pattern 4: Sentinel-Controlled

int num;
printf("Enter numbers (-1 to stop):\n");

while (1) {
    scanf("%d", &num);
    if (num == -1) break;
    printf("You entered: %d\n", num);
}

Pattern 5: Flag-Controlled

int found = 0;
int target = 42;

for (int i = 0; i < size && !found; i++) {
    if (arr[i] == target) {
        found = 1;
        printf("Found at index %d\n", i);
    }
}

🔁 Infinite Loops

Sometimes you need a loop that runs forever:

// Using for
for (;;) {
    // use break to exit
}

// Using while
while (1) {
    // use break to exit
}

// Using do-while
do {
    // use break to exit
} while (1);

Common Uses:

  • Game loops
  • Server main loops
  • Embedded systems
  • Event-driven programs

🧮 Loop Examples

Sum of Numbers:

int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
printf("Sum 1-100 = %d\n", sum);  // 5050

Factorial:

int n = 5;
long factorial = 1;
for (int i = 2; i <= n; i++) {
    factorial *= i;
}
printf("%d! = %ld\n", n, factorial);  // 120

Power:

int base = 2, exp = 10;
long result = 1;
for (int i = 0; i < exp; i++) {
    result *= base;
}
printf("%d^%d = %ld\n", base, exp, result);  // 1024

Fibonacci:

int n = 10, a = 0, b = 1;
printf("%d %d ", a, b);
for (int i = 2; i < n; i++) {
    int next = a + b;
    printf("%d ", next);
    a = b;
    b = next;
}

Prime Check:

int num = 17, isPrime = 1;
for (int i = 2; i * i <= num; i++) {
    if (num % i == 0) {
        isPrime = 0;
        break;
    }
}
printf("%d is %sprime\n", num, isPrime ? "" : "not ");

⚠️ Common Mistakes

1. Off-by-One Errors:

// WRONG: prints 0-10 (11 numbers)
for (int i = 0; i <= 10; i++)

// CORRECT: prints 0-9 (10 numbers)
for (int i = 0; i < 10; i++)

2. Infinite Loop (Unintended):

// WRONG: i never changes
int i = 0;
while (i < 10) {
    printf("%d\n", i);
    // forgot i++;
}

// WRONG: wrong comparison
for (int i = 10; i >= 0; i++) {  // Should be i--
    printf("%d\n", i);
}

3. Semicolon After for/while:

// WRONG: empty loop, block always executes
for (int i = 0; i < 10; i++);
{
    printf("%d\n", i);  // Only runs once!
}

// CORRECT
for (int i = 0; i < 10; i++) {
    printf("%d\n", i);
}

4. Modifying Loop Variable:

// Confusing and error-prone
for (int i = 0; i < 10; i++) {
    if (condition) i = 5;  // Avoid this!
}

🔄 Loop Equivalents

Any loop type can be rewritten as another:

for as while:

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

// Equivalent while
int i = 0;
while (i < 5) {
    printf("%d ", i);
    i++;
}

while as for:

// while loop
int x = 10;
while (x > 0) {
    printf("%d ", x);
    x--;
}

// Equivalent for
for (int x = 10; x > 0; x--) {
    printf("%d ", x);
}

✅ Best Practices

  1. Use for when iteration count is known
  2. Use while when iteration count depends on condition
  3. Use do-while when body must execute at least once
  4. Avoid modifying loop variable inside body
  5. Keep loop body simple - extract to functions if complex
  6. Be careful with floating-point loop counters
  7. Use meaningful loop variable names for complex loops
  8. Comment non-obvious loop termination conditions

🔑 Key Takeaways

  1. for - counter-based, known iterations
  2. while - condition-based, pre-test loop
  3. do-while - post-test, executes at least once
  4. All loops can be converted to each other
  5. Avoid infinite loops (unless intended)
  6. Watch for off-by-one errors
  7. Don't forget to update loop variables

⏭️ Next Topic

Continue to break, continue, and goto for loop control statements.

README - C Programming Tutorial | DeepML