NBC 103 • Unit 216 min readHigh Exam Frequency

Iterative Statements: while, do-while & for Loops

Unit 2: Control Statements, Loops & Modular FunctionsProblem Solving Using C

👨‍🏫 Professor's Mental Model: The Athletic Track Lap Runner vs Amusement Park Ticket Turnstile

Loop ek aisi process hai jo ek kaam ko baar-baar repeat karti hai jab tak target achieve na ho. Entry-controlled loop (for aur while) ek strict exam hall guard jaisa hai: pehle admit card check karega, agar valid hai tabhi andar jane dega (0 iterations possible). Jabki Exit-controlled loop (do-while) ek roller coaster jaisa hai: pehle aapko ek ride lene deta hai, fir bahar nikalte waqt ticket check karta hai—isliye do-while kam se kam 1 baar zaroor execute hota hai!

Academic Lecture Notes & Solved Study Pages

Unit 2 • Core Concepts, Step-by-Step Proofs & Notebook Solutions

4 Notebook Pages
NOTEBOOK PAGE 1 OF 4

1. The 4 Fundamental Elements of Every Loop

Every reliable loop in computer science requires 4 coordinated components:

1. Initialization: Setting up loop counter variables prior to starting (e.g., `int i = 1;`). 2. Test Condition: Boolean condition evaluated on each iteration (e.g., `i <= 10;`). 3. Loop Body: The payload instructions repeated during each valid cycle. 4. Update Expression: Modifying the counter (increment `i++` or decrement `i--`) ensuring progress toward loop termination and preventing infinite lockups.

NOTEBOOK PAGE 2 OF 4

2. Entry-Controlled Loops: while vs for

while Loop:

Pre-test loop. Condition checked at the TOP before executing loop body.

Ideal when the exact total number of iterations is unknown in advance and depends on dynamic runtime conditions (e.g., reading until EOF or reversing digits of an unknown number).

for Loop:

Compact loop consolidating initialization, condition, and update in a single line:

`for (init; condition; update) { ... }`

Execution Sequence: 1. Init (once) -> 2. Condition Check -> 3. Execute Body -> 4. Update -> Repeat from Step 2.

Multiple variables can be initialized or updated using comma operators: `for (i=0, j=10; i<j; i++, j--)`.

NOTEBOOK PAGE 3 OF 4

3. Exit-Controlled Loop: do-while Loop

Syntax: do { statements; } while (condition);

The loop body executes FIRST, and the condition is tested at the BOTTOM.
Guarantee: Executes AT LEAST ONCE even if the condition is false on the very first evaluation.
Semicolon Requirement: Notice the mandatory trailing semicolon `;` after `while(condition);`.
Ideal for interactive programs: Prompting the user 'Do you want to continue (y/n)?' or menu displays.
NOTEBOOK PAGE 4 OF 4

4. Infinite Loops & Nested Loop Patterns

Intentional Infinite Loops: `for (;;) { ... }` and `while (1) { ... }` are commonly used in operating system event loops, servers, and microcontrollers. They are terminated via internal `break` conditions.
Nested Loops: Placing one loop inside another. The inner loop executes completely for EVERY single iteration of the outer loop. Time complexity multiplies: $O(Rows \times Cols) = O(N^2)$.
Master Loop Comparative Analysis: for vs while vs do-while
Featurefor Loopwhile Loopdo-while Loop
Control TypeEntry-Controlled (Pre-test)Entry-Controlled (Pre-test)Exit-Controlled (Post-test)
Condition CheckAt the top before loop bodyAt the top before loop bodyAt the bottom after loop body
Minimum Iterations0 (Zero)0 (Zero)1 (At least once guaranteed)
Trailing SemicolonNo (only inside header)No semicolon after while()Mandatory semicolon: while();
Best Use CaseDeterministic iterations known in advance (arrays, counts)Indeterminate iterations depending on conditionsMenu loops, retry prompts, user validation

Interactive Tested Code Example

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    // 1. Number Palindrome Check using while loop
    int num = 12321, original = num, reversed = 0, rem;
    while (num > 0) {
        rem = num % 10;
        reversed = (reversed * 10) + rem;
        num /= 10;
    }
    printf("Original: %d | Reversed: %d\n", original, reversed);
    if (original == reversed)
        printf("Result: %d is a PALINDROME number.\n\n", original);

    // 2. Floyd's Triangle using Nested for loops
    int rows = 4, count = 1;
    printf("Floyd's Triangle Pattern (%d rows):\n", rows);
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%-3d ", count++);
        }
        printf("\n");
    }
    return 0;
}
💡 Note:Demonstrates an indeterminate while loop to mathematically reverse an integer for palindrome verification, alongside nested for loops generating Floyd's Triangle.

🎯 University Exam Scoring Blueprint

  • In exam questions, always point out that do-while has a mandatory semicolon at the end: while(cond);
  • Explain the minimum execution count: for/while is 0, do-while is 1.
  • Be ready to write both for(;;) and while(1) when asked to show infinite loop syntax.

Top Viva Questions on Iterative Statements: while, do-while & for Loops

2 Questions
1

What is the output of: int i = 10; do { printf("%d ", i); i++; } while(i < 5);?

2

Can any expression in a for loop header: for(e1; e2; e3) be omitted?