IT232 C Programming

C ProgrammingUnit 510 min read

Control Structures: Iteration and Loops

Unit 5 of C Programming: Explores how loops (for, while, do-while) automate repetitive tasks, their differences, nested loops, loop control (break, continue), and practical applications like pattern printing, number series, and user input validation.

TAKEAWAYS:

  • Loops reduce repetitive code by executing a block of statements repeatedly until a condition is met.
  • for loops are ideal for count-controlled iterations (e.g., printing numbers 1–10), while while and do-while handle condition-controlled loops (e.g., user input validation).
  • Nested loops enable multi-dimensional tasks (e.g., printing patterns, matrix operations) by embedding one loop inside another.
  • Loop control statements (break, continue) modify loop flow to exit early or skip iterations.
  • Infinite loops occur when loop conditions are never false (e.g., while(1)), requiring careful design.
  • Real-world loops optimize performance (e.g., Daraz’s order processing) and user interaction (e.g., Khalti’s payment retries).

1. Introduction to Iteration

Iteration is the repetition of a process until a specific condition is satisfied. In C, loops automate iteration, eliminating manual repetition of code blocks. Loops are classified based on their trigger condition:

  • Pre-test loops: Check condition before execution (e.g., while, for).
  • Post-test loops: Execute at least once, then check condition (e.g., do-while).

Why loops?

  • Save time by avoiding manual repetition.
  • Handle dynamic data (e.g., user-defined limits).
  • Enable complex patterns (e.g., game grids, financial calculations).

2. Types of Loops in C

A. for Loop

Syntax:

for (initialization; condition; increment/decrement) {
    // loop body
}

How it works:

  1. Initialization: Runs once (e.g., int i = 1).
  2. Condition: Checked before each iteration (e.g., i <= 10).
  3. Increment/Decrement: Executes after each iteration (e.g., i++).
  4. Loop stops when condition becomes false.

Example: Print multiples of 5 < 100

flowchart TD
    A["Start"] --> B["Initialize i = 5"]
    B --> C{"Is i < 100?"}
    C -->|"Yes"| D["Print i"]
    D --> E["i = i + 5"]
    E --> C
    C -->|"No"| F["End"]
#include <stdio.h>
int main() {
    for (int i = 5; i < 100; i += 5) {
        printf("%d ", i);
    }
    return 0;
}

Trace Table:

Iteration i (value) Condition (i < 100) Output
1 5 True 5
2 10 True 10
... ... ... ...
19 95 True 95
20 100 False End

B. while Loop

Syntax:

while (condition) {
    // loop body
}

Key difference from for:

  • No built-in initialization or increment.
  • Condition checked before each iteration (risk of infinite loop if condition never becomes false).

Example: Sum of digits of a number

flowchart TD
    A["Start"] --> B["Input number n = 123"]
    B --> C["Initialize sum = 0, temp = n"]
    C --> D{"Is temp != 0?"}
    D -->|"Yes"| E["sum += temp % 10"]
    E --> F["temp = temp / 10"]
    F --> D
    D -->|"No"| G["Print sum"]
    G --> H["End"]
#include <stdio.h>
int main() {
    int n, sum = 0, temp;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    while (temp != 0) {
        sum += temp % 10;
        temp /= 10;
    }
    printf("Sum of digits: %d\n", sum);
    return 0;
}

Trace:

  • Input: 123
  • Iteration 1: sum = 0 + 3 = 3, temp = 12
  • Iteration 2: sum = 3 + 2 = 5, temp = 1
  • Iteration 3: sum = 5 + 1 = 6, temp = 0 → Loop ends.
  • Output: 6

C. do-while Loop

Syntax:

do {
    // loop body
} while (condition);

Key difference:

  • Post-test loop: Executes at least once, then checks condition.
  • Useful for menu-driven programs (e.g., Khalti’s payment retry system).

Example: Menu-driven calculator

flowchart TD
    A["Start"] --> B["Display menu"]
    B --> C["Get user choice"]
    C --> D{"Is choice valid?"}
    D -->|"Yes"| E["Perform operation"]
    E --> B
    D -->|"No"| F["Print 'Invalid choice'"]
    F --> B
#include <stdio.h>
int main() {
    int choice;
    do {
        printf("\n1. Add\n2. Subtract\n3. Exit\nChoice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: printf("Addition\n"); break;
            case 2: printf("Subtraction\n"); break;
            case 3: break;
            default: printf("Invalid choice!\n");
        }
    } while (choice != 3);
    return 0;
}

Trace:

  • User enters 1 → "Addition" → loop repeats.
  • User enters 4 → "Invalid choice!" → loop repeats.
  • User enters 3 → loop exits.

3. Loop Control Statements

A. break

  • Exits the loop immediately, even if the condition is true.
  • Used to skip remaining iterations when a condition is met.

Example: Find first even number

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        printf("First even number: %d\n", i);
        break;  // Exit loop after finding the first even number
    }
}

Output:

First even number: 2

B. continue

  • Skips the current iteration and moves to the next.
  • Useful for filtering data (e.g., skipping odd numbers).

Example: Print even numbers only

for (int i = 1; i <= 10; i++) {
    if (i % 2 != 0) {
        continue;  // Skip odd numbers
    }
    printf("%d ", i);  // Print even numbers
}

Output:

2 4 6 8 10

4. Nested Loops

A loop inside another loop, creating multi-dimensional repetition. Use cases:

  • Printing patterns (e.g., right-angled triangles).
  • Processing matrices (e.g., 2D arrays in Daraz’s inventory).
  • Simulating games (e.g., Pathao’s route optimization).

Example: Print the pattern

BIMMIB
IMMI
MM
flowchart TD
    A["Start"] --> B["Outer loop: rows = 3"]
    B --> C["Inner loop: columns = 5 - row"]
    C --> D["Print 'M' or 'I' based on column"]
    D --> C
    B --> E["Decrement row"]
    E --> C
    C --> F["End"]
#include <stdio.h>
int main() {
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 5 - row; col++) {
            if (col % 2 == 0) {
                printf("M");
            } else {
                printf("I");
            }
        }
        printf("\n");
    }
    return 0;
}

Trace:

  • Row 0: col = 0 → 'M', col = 1 → 'I', col = 2 → 'M', col = 3 → 'I', col = 4 → 'B' (if adjusted). Output: MIMIM (adjust logic for exact pattern).
  • Row 1: col = 0 → 'M', col = 1 → 'I', col = 2 → 'M'. Output: MIM.
  • Row 2: col = 0 → 'M', col = 1 → 'M'. Output: MM.

5. Infinite Loops

Occurs when the loop condition never becomes false. Common causes:

  • Missing increment/decrement (e.g., for (int i = 0; ; i++)).
  • Incorrect condition (e.g., while (i > 0) with i never decreasing).

Example: Infinite loop (accidental)

for (int i = 0; i < 10; ) {
    printf("%d ", i);
    // Missing i++ → infinite loop!
}

Fix: Add i++ to the loop.


6. Comparison Table: for, while, do-while

Feature for Loop while Loop do-while Loop
Initialization Inside loop header Outside loop body Outside loop body
Condition Check Before iteration Before iteration After iteration
Execution Guarantee Depends on condition May not execute Executes at least once
Use Case Count-controlled loops Condition-controlled loops Menu-driven programs
Example Printing numbers 1–10 User input validation Khalti’s retry mechanism

7. Real-World Applications

## In the real world

  1. Daraz Order Processing

    • Idea: while loops handle pending orders until all are processed.
    • How: Daraz’s backend uses loops to check inventory and update order statuses dynamically.
    • Worked Example: A loop iterates through order_list until order_list[i].status == "Delivered".
      while (order_list[i].status != "Delivered") {
          update_status(order_list[i].id);
          i++;
      }
      
  2. Khalti Payment Retries

    • Idea: do-while ensures at least one payment attempt, then retries if failed.
    • How: The loop continues until the transaction succeeds or max retries are reached.
      do {
          if (process_payment()) {
              break;  // Success
          }
          retries++;
      } while (retries < 3);
      
  3. NTC Traffic Light Control

    • Idea: for loops simulate timed cycles for traffic lights.
    • How: A loop runs for 30 seconds (green), then switches to yellow/red.
      for (int sec = 0; sec < 30; sec++) {
          display_light("Green");
      }
      

8. Common Mistakes and Debugging

Mistake Cause Fix
Infinite loop Missing increment/decrement Add i++ or i--
Off-by-one error Incorrect loop bounds Test with printf
Uninitialized loop variable Variable not declared Initialize in loop header (for (int i=0))
Skipping loop body Missing braces {} Add braces for single-line loops

9. Exam Tip

  • Focus on:
    • Differentiating loops: Know when to use for, while, or do-while (e.g., for for fixed iterations, while for dynamic conditions).
    • Nested loops: Practice pattern printing (e.g., right-angled triangles, alphabets).
    • Loop control: Use break/continue to exit or skip iterations (common in exam questions).
    • Infinite loops: Avoid them by ensuring loop conditions change.
  • Common Exam Questions:
    • Write a program to print a specific pattern (e.g., pyramid, diamond).
    • Find the sum of digits of a number using while.
    • Calculate the area of a rectangle with nested loops (though simpler with multiplication).
    • Differentiate while and do-while with a menu-driven example.
  • Marking Scheme:
    • Correct logic: 40%
    • Proper loop syntax: 30%
    • Output correctness: 20%
    • Code readability: 10%

Practice Problem: Write a program to print the following pattern:

1
1 2
1 2 3
1 2 3 4

Hint: Use nested for loops with an inner loop for printing numbers.

Based on the TU BITM syllabus for C Programming (IT232), unit 5.

Discussion

Loading…