BIT102 C Programming

C ProgrammingUnit 411 min read

Loops & Pattern Printing: Control Flow & Creative Output

Unit 4 of C Programming: Explores loops (for, while, do-while), their syntax, logic, and applications in pattern printing, with real-world ties to algorithms used in apps like Daraz’s order processing and NTC’s call routing.

TAKEAWAYS:

  • Master for, while, and do-while loops to automate repetitive tasks with precise control over iterations.
  • Use loops to generate patterns (alphanumeric, geometric) by breaking them into nested loop logic and arithmetic progression.
  • Apply loops to real-world problems like calculating averages, finding min/max values, or simulating queues (e.g., Pathao driver assignments).
  • Debug loops by tracing variable changes step-by-step, especially in nested loops for patterns.
  • Compare loop types using a table of when to use each (e.g., for loops for fixed iterations, while for condition-dependent loops).
  • Practice pattern printing by decomposing designs into smaller sub-patterns (e.g., right-angled triangles, pyramids).

1. Introduction to Loops

Loops in C allow repetition of code blocks without rewriting them. They eliminate redundancy and enable efficient processing of large datasets. Loops are classified into three types:

  • for loop: Best for known iterations (e.g., printing numbers 1 to 10).
  • while loop: Runs while a condition is true (e.g., reading input until a sentinel value).
  • do-while loop: Executes at least once, then checks the condition (e.g., menu-driven programs).

2. For Loop

Structure

flowchart TD
    A["for (init; condition; increment)"] --> B["{ Code block }"]
    B --> C["Check condition"]
    C -->|"True"| B
    C -->|"False"| D["Exit loop"]

Syntax

for (initialization; condition; increment/decrement) {
    // Loop body
}
  • Initialization: Runs once at the start (e.g., int i = 1).
  • Condition: Checked before each iteration (e.g., i <= 5).
  • Increment/Decrement: Executes after each iteration (e.g., i++).

Example: Reverse a Number

Task: Reverse the digits of a user-input number (e.g., 1234 → 4321).

#include <stdio.h>
int main() {
    int num, reversed = 0, remainder;
    printf("Enter a number: ");
    scanf("%d", &num);

    for (; num != 0; num /= 10) {  // Loop until num becomes 0
        remainder = num % 10;       // Extract last digit
        reversed = reversed * 10 + remainder;  // Build reversed number
    }
    printf("Reversed number: %d\n", reversed);
    return 0;
}

Trace Table:

Iteration num (before /= 10) remainder (num % 10) reversed (reversed * 10 + remainder)
1 1234 4 0 * 10 + 4 = 4
2 123 3 4 * 10 + 3 = 43
3 12 2 43 * 10 + 2 = 432
4 1 1 432 * 10 + 1 = 4321
5 0 - Loop ends

Key Insight:

  • The loop terminates when num becomes 0 (e.g., after 1234 / 10 = 123).
  • Modulo (%) extracts the last digit; division (/) removes it.

3. While Loop

Structure

flowchart TD
    A["while (condition)"] --> B["{ Code block }"]
    B --> C["Check condition"]
    C -->|"True"| B
    C -->|"False"| D["Exit loop"]

Syntax

while (condition) {
    // Loop body
}
  • No initialization or increment inside the loop body (unless explicitly written).
  • Risk: Infinite loop if condition never becomes false.

Example: Find Min/Max Age in a Class

Task: Read ages of 20 students and find the minimum and maximum age.

#include <stdio.h>
int main() {
    int ages[20], min, max, i;
    printf("Enter ages of 20 students:\n");
    for (i = 0; i < 20; i++) scanf("%d", &ages[i]);

    min = max = ages[0];  // Initialize with first element
    for (i = 1; i < 20; i++) {
        if (ages[i] < min) min = ages[i];
        if (ages[i] > max) max = ages[i];
    }
    printf("Min age: %d, Max age: %d\n", min, max);
    return 0;
}

Trace for First 3 Ages (22, 18, 25):

Iteration Current Min Current Max New Age Update Min/Max?
0 (init) 22 22 - -
1 22 22 18 Min → 18
2 18 22 25 Max → 25

4. Do-While Loop

Structure

flowchart TD
    A["do { Code block }"] --> B["while (condition)"]
    B -->|"True"| A
    B -->|"False"| C["Exit loop"]

Syntax

do {
    // Loop body
} while (condition);
  • Guaranteed execution at least once.
  • Used for menu-driven programs or input validation.

Example: Menu-Driven Calculator

#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;
}

5. Comparison of Loops

Feature for Loop while Loop do-while Loop
Initialization Inside loop header Outside loop Outside loop
Condition Check Before iteration Before iteration After iteration
Use Case Fixed iterations Dynamic conditions At least one run
Example Printing 1 to 10 Reading input until EOF Menu loops

6. Pattern Printing

Patterns are generated using nested loops and arithmetic progression. Break patterns into smaller sub-patterns.

Pattern 1: Right-Angled Triangle (Numbers)

Task: Print

1
1 2
1 2 3
1 2 3 4

Approach:

  • Outer loop controls rows (i).
  • Inner loop prints numbers from 1 to i.
1021324354
Output of the right-angled triangle pattern (numbers) for 5 rows.
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

State After Each Row:

After i=1: 1
After i=2: 1 2
After i=3: 1 2 3
After i=4: 1 2 3 4

Pattern 2: Alphabetical Pyramid ("BITTU BITT BIT BI B")

Task: Print

B I T T U
  B I T T
    B I T
      B I
        B

Approach:

  • Use char and ASCII values ('B' + i).
  • Spaces: n - i (where n is total rows).
B0BIT1BITT2BITTU3BITTU B4BITTU BIT5BITTU BITT6BITTU BITT BI7BITTU BITT BIT8
Output of the alphabetical pyramid pattern for 5 levels.
int n = 5;
for (int i = 0; i < n; i++) {
    // Print spaces
    for (int s = 0; s < n - i - 1; s++) printf("  ");
    // Print letters
    for (int j = 0; j <= i; j++) {
        printf("%c ", 'B' + j);
    }
    printf("\n");
}

State After Each Row:

i=0: "B" (no spaces)
i=1: "  B I"
i=2: "    B I T"
i=3: "      B I T T"
i=4: "        B I T T U"

Pattern 3: Integer Sequence (1 1 2 1 2 3 1 2 3 4 1 2 3 4 5)

Task: Print the sequence above. Approach:

  • Outer loop runs for n rows (n=5).
  • Inner loop prints numbers from 1 to i.
10112213243516273849110211312413514
Output of the integer sequence pattern for 5 rows.
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

But wait! This doesn’t match the given sequence. Let’s adjust: The sequence is pyramid-like but with overlapping rows. Use a double loop with j starting from 1 to n and print j if j <= i.

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        if (j <= i) printf("%d ", j);
    }
    printf("\n");
}

State After Each Row:

i=1: 1
i=2: 1 2
i=3: 1 2 3
i=4: 1 2 3 4
i=5: 1 2 3 4 5

Correction: The original sequence is a right-angled triangle with increasing rows. To match exactly, use:

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

But the given sequence is:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

This is identical to the first pattern! The question likely expects this.


7. Real-World Applications

In the Real World

  1. Daraz Order Processing:

    • Idea: Loops process multiple orders in a queue (FIFO).
    • How: A while loop checks for new orders until the queue is empty.
    • Example: A for loop iterates through n orders, updating inventory and status.
  2. NTC Call Routing:

    • Idea: Loops route calls to available agents (like a do-while loop ensuring a call is answered).
    • How: A while loop checks agent availability; if none, it queues the call.
  3. Pathao Driver Assignment:

    • Idea: Loops assign drivers to nearby riders (nested loops for proximity checks).
    • How: Outer loop iterates through riders; inner loop checks driver availability.

8. Exam Tips

  1. Loop Structure:

    • Always include initialization, condition, and increment in for loops.
    • For while/do-while, clearly state the termination condition.
  2. Pattern Printing:

    • Decompose the pattern into smaller parts (e.g., rows, columns).
    • Use tables to show the state after each iteration (as above).
  3. Common Mistakes:

    • Infinite loops: Forgetting to update the loop variable (e.g., missing i++).
    • Off-by-one errors: Incorrect bounds (e.g., i <= n vs i < n).
  4. Practice Questions:

    • Reverse a number: Use modulo and division.
    • Patterns: Start with simple shapes (triangles, squares) before complex ones.
    • Real-world ties: Relate loops to apps (e.g., "How would you use a loop in Daraz’s inventory system?").
  5. Code Writing:

    • Indent properly to show nested loops.
    • Comment key steps (e.g., // Extract last digit).

9. Worked Example: Average Age with Loops

Task: Calculate the average age of 20 students using loops.

#include <stdio.h>
int main() {
    int ages[20], sum = 0, i;
    float avg;
    printf("Enter ages of 20 students:\n");
    for (i = 0; i < 20; i++) {
        scanf("%d", &ages[i]);
        sum += ages[i];  // Accumulate sum
    }
    avg = (float)sum / 20;  // Cast to float for division
    printf("Average age: %.2f\n", avg);
    return 0;
}

Trace for Ages [22, 18, 20, ..., 25]:

Iteration sum (after +=) Average Calculation
0 22 -
1 40 (22+18) -
... 400 (sum of all) 400 / 20 = 20.0

10. Summary Flowchart for Loop Selection

flowchart TD
    A["Need fixed iterations?"] -->|"Yes"| B["Use for loop"]
    A -->|"No"| C["Need condition check before iteration?"]
    C -->|"Yes"| D["Use while loop"]
    C -->|"No"| E["Use do-while loop"]

Based on the TU BIT syllabus for C Programming (BIT102), unit 4.

Discussion

Loading…