PROJECTENGRAM

ITERATIVE STATEMENTS IN C

Iterative Statements in C

Tags: #◇Code Snippets #◇CCPROG1 #◇Loops #◇C #◇M6


◇Overview

Iterative statements, commonly known as loops, allow a specific block of code to be executed repeatedly as long as a certain condition remains true. They are essential for tasks involving repetition without writing redundant code.

◇Key Definitions

Loop: A programming construct that repeats a block of code. while Loop: Repeats while a condition is true, checks condition before execution. do-while Loop: Executes the block at least once, checks condition after execution. for Loop: A compact loop structure combining initialization, condition check, and update. Infinite Loop: A loop whose condition never becomes false.

◇Code Implementation

『』
C
#include <stdio.h>

int main() {
    // 1. while loop
    int i = 0;
    while (i < 3) {
        printf("While loop count: %d\n", i);
        i++;
    }
    
    // 2. do-while loop
    int j = 0;
    do {
        printf("Do-while count: %d\n", j);
        j++;
    } while (j < 3);
    
    // 3. for loop
    for (int k = 0; k < 3; k++) {
        printf("For loop count: %d\n", k);
    }
    
    return 0;
}

◇Syntax Breakdown

while(condition): The condition is tested at the start. If false initially, the loop body never runs. do { ... } while(condition);: The body runs, then condition is checked. Notice the required semicolon ; at the end. for(initialization; condition; update): Best used when the number of iterations is known beforehand.

◇Common Pitfalls

Off-by-One Error: Iterating one time too many or one time too few (e.g., using <= instead of <). Infinite Loops: Forgetting to update the loop control variable (e.g., forgetting i++). Semicolon After For/While: for(int i=0; i<10; i++); { ... } The semicolon terminates the loop immediately, making the following block run only once, separated from the loop.

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

How many times will the body of the loop for (int i = 0; i < 5; i++) execute?

Q2

What is the fundamental difference between a while loop and a do-while loop in C?

Q3

Inside a for loop (for (init; cond; update)), what happens immediately after a continue; statement is executed inside the loop body?

Q4

What is the effect of placing a stray semicolon immediately after a while condition, such as int i = 0; while (i < 10); { i++; }?

Q5

Which loop construct is most idiomatic when the exact number of iterations is known before entering the loop?