Skip to main content

Conditional Iteration (while)

Description

A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. Unlike a for loop, where the number of iterations is typically known in advance, a while loop is used when the number of repetitions depends on a dynamic condition that may change during execution.

The general structure of a while loop involves three components:

  1. Initialization — Set up a variable (often called a loop counter or control variable) before the loop begins.
  2. Condition Check — Before each iteration, the loop evaluates a boolean condition. If it is true, the loop body executes. If it is false, the loop terminates and the program continues to the next statement after the loop.
  3. Update — Inside the loop body, the control variable (or the condition itself) must be updated so that the loop eventually terminates.

A while loop is sometimes called a pre-test loop because the condition is checked before the body runs. This means if the condition is false from the very beginning, the loop body will never execute — not even once.

Common use cases for while loops include:

  • Reading input until a sentinel value is encountered
  • Searching for an element in a collection when you do not know how many checks are needed
  • Running a game loop until a player wins or loses
  • Processing data until a queue or stream is empty
  • Repeating a calculation until a desired precision or convergence is reached

Key danger: If the condition never becomes false, the loop runs forever — this is called an infinite loop. Always ensure that something inside the loop body moves the program closer to making the condition false.

Examples

Example 1

Task: Print all integers from 1 to 5 using a while loop.

Input: None (the range is hard-coded)

Output:

1 2 3 4 5

Explanation: We initialize a counter variable i to 1. The while loop checks whether i ≤ 5. Since 1 ≤ 5 is true, the loop body prints 1 and increments i to 2. This repeats: 2 is printed and i becomes 3, then 3 is printed and i becomes 4, then 4 is printed and i becomes 5, then 5 is printed and i becomes 6. Now the condition 6 ≤ 5 is false, so the loop stops. We printed exactly five numbers.

Example 2

Task: Compute the sum of all integers from 1 to n using a while loop, where n = 4.

Input: n = 4

Output:

10

Explanation: We initialize sum = 0 and i = 1. Each iteration adds the current value of i to sum and increments i by 1. The loop continues while i ≤ 4.

  • Iteration 1: sum = 0 + 1 = 1, i becomes 2
  • Iteration 2: sum = 1 + 2 = 3, i becomes 3
  • Iteration 3: sum = 3 + 3 = 6, i becomes 4
  • Iteration 4: sum = 6 + 4 = 10, i becomes 5
  • Condition check: 5 ≤ 4 is false → loop ends

Final sum = 10, which is indeed 1 + 2 + 3 + 4.

Example 3

Task: Count the number of digits in a positive integer using a while loop, where the number is 4821.

Input: number = 4821

Output:

4

Explanation: We initialize count = 0 and repeatedly divide the number by 10 (integer division) until it reaches 0.

  • Iteration 1: number = 4821 ÷ 10 = 482, count = 1
  • Iteration 2: number = 482 ÷ 10 = 48, count = 2
  • Iteration 3: number = 48 ÷ 10 = 4, count = 3
  • Iteration 4: number = 4 ÷ 10 = 0, count = 4
  • Condition check: number > 0 is false (number is 0) → loop ends

The result is 4, confirming that 4821 has four digits. Notice that the number of iterations was unknown at the start — it depended on the magnitude of the input. This is exactly why a while loop fits better than a for loop here.

Constraints

  • While loops are supported in virtually all programming languages (C, C++, Python, Java, JavaScript, etc.)
  • The condition expression must evaluate to a boolean (true/false)
  • The loop body must eventually make the condition false to avoid infinite loops
  • In Python, there is no native do-while loop, but the same behavior can be simulated using while True with a break statement
  • C++, Java, and C also support a do-while variant where the body executes at least once before the condition is checked

Editorial

Basic While Loop — Counting with a Counter Variable

Intuition

The simplest use of a while loop is counting. Imagine you are standing at the bottom of a staircase and you need to climb exactly 5 steps. Before climbing, you check: "Have I reached step 5 yet?" If not, you climb one step and check again. You keep doing this until you have climbed all 5 steps.

In programming, this translates to:

  1. Set a counter to 1 (we start at step 1).
  2. Ask: "Is the counter ≤ 5?" (pre-test condition)
  3. If yes, print the counter and increase it by 1.
  4. Go back to step 2.
  5. If no, stop.

The three essential ingredients are: initialize the counter before the loop, check the condition at the top of the loop, and update the counter inside the loop body. If you forget the update step, the counter stays at 1 forever, and you have an infinite loop.

Step-by-Step Explanation

Let's trace through printing numbers 1 to 5 using a while loop:

Step 1: Initialize i = 1. This is done once, before the loop starts.

Step 2: Check condition: Is i ≤ 5? Since 1 ≤ 5 is true, enter the loop body.

Step 3: Execute body: Print 1. Then update i = i + 1, so i becomes 2.

Step 4: Check condition: Is 2 ≤ 5? True. Print 2. Update i to 3.

Step 5: Check condition: Is 3 ≤ 5? True. Print 3. Update i to 4.

Step 6: Check condition: Is 4 ≤ 5? True. Print 4. Update i to 5.

Step 7: Check condition: Is 5 ≤ 5? True. Print 5. Update i to 6.

Step 8: Check condition: Is 6 ≤ 5? False. Exit the loop.

Output: 1 2 3 4 5

While Loop — Counting from 1 to 5 — Watch how the counter variable i progresses through each iteration. The condition is checked before every iteration, and the loop exits when the condition becomes false.

Algorithm

  1. Initialize a counter variable i to 1
  2. While i is less than or equal to 5:
    a. Print the value of i
    b. Increment i by 1
  3. The loop automatically terminates when i exceeds 5

Code

#include <iostream>
using namespace std;

int main() {
    int i = 1;          // Step 1: Initialize counter
    
    while (i <= 5) {    // Step 2: Check condition before each iteration
        cout << i << " "; // Print current value
        i++;             // Step 3: Update counter (CRITICAL — prevents infinite loop)
    }
    // After loop: i is now 6
    cout << endl;
    return 0;
}
// Output: 1 2 3 4 5
i = 1               # Step 1: Initialize counter

while i <= 5:       # Step 2: Check condition before each iteration
    print(i, end=" ")  # Print current value
    i += 1           # Step 3: Update counter (CRITICAL — prevents infinite loop)

# After loop: i is now 6
print()
# Output: 1 2 3 4 5
public class WhileLoopBasic {
    public static void main(String[] args) {
        int i = 1;          // Step 1: Initialize counter
        
        while (i <= 5) {    // Step 2: Check condition before each iteration
            System.out.print(i + " "); // Print current value
            i++;             // Step 3: Update counter (CRITICAL — prevents infinite loop)
        }
        // After loop: i is now 6
        System.out.println();
    }
}
// Output: 1 2 3 4 5

Complexity Analysis

Time Complexity: O(n)

The loop runs exactly n times (in this case n = 5). Each iteration performs a constant amount of work: one print operation and one increment. So the total time grows linearly with the number of iterations.

Space Complexity: O(1)

We only use a single integer variable i as the counter. No additional memory is allocated that grows with the input size.

Accumulation with While Loop — Summing a Series

Intuition

Beyond simple counting, while loops are commonly used for accumulation — building up a result across iterations. Think of filling a piggy bank: each day you add some coins, and you keep track of the running total. You stop when you have added all the coins you intended.

In this pattern, we introduce an accumulator variable (like sum) that starts at a neutral value (0 for addition, 1 for multiplication) and grows with each iteration. The counter variable still controls when to stop, but the accumulator captures the result.

This pattern is the foundation for many real-world computations: computing averages, factorials, finding products, and even building strings character by character.

Step-by-Step Explanation

Let's trace computing the sum of integers from 1 to 4 (so n = 4):

Step 1: Initialize sum = 0 and i = 1. The sum starts at 0 because we have not added anything yet.

Step 2: Check: Is 1 ≤ 4? Yes. Execute body: sum = 0 + 1 = 1. Increment i to 2.

Step 3: Check: Is 2 ≤ 4? Yes. Execute body: sum = 1 + 2 = 3. Increment i to 3.

Step 4: Check: Is 3 ≤ 4? Yes. Execute body: sum = 3 + 3 = 6. Increment i to 4.

Step 5: Check: Is 4 ≤ 4? Yes. Execute body: sum = 6 + 4 = 10. Increment i to 5.

Step 6: Check: Is 5 ≤ 4? No. Exit loop.

Result: sum = 10

While Loop — Accumulating Sum from 1 to 4 — Watch how the accumulator variable sum grows with each iteration as we add the current value of i to it.

Algorithm

  1. Initialize sum = 0 (accumulator) and i = 1 (counter)
  2. While i ≤ n:
    a. Add i to sum
    b. Increment i by 1
  3. After the loop, sum holds the total

Code

#include <iostream>
using namespace std;

int main() {
    int n = 4;
    int sum = 0;          // Accumulator starts at 0
    int i = 1;            // Counter starts at 1
    
    while (i <= n) {      // Loop while counter is within range
        sum += i;         // Add current counter value to sum
        i++;              // Move counter forward
    }
    
    cout << "Sum = " << sum << endl;  // Output: Sum = 10
    return 0;
}
n = 4
sum_val = 0           # Accumulator starts at 0
i = 1                 # Counter starts at 1

while i <= n:         # Loop while counter is within range
    sum_val += i      # Add current counter value to sum
    i += 1            # Move counter forward

print(f"Sum = {sum_val}")  # Output: Sum = 10
public class WhileLoopSum {
    public static void main(String[] args) {
        int n = 4;
        int sum = 0;          // Accumulator starts at 0
        int i = 1;            // Counter starts at 1
        
        while (i <= n) {      // Loop while counter is within range
            sum += i;         // Add current counter value to sum
            i++;              // Move counter forward
        }
        
        System.out.println("Sum = " + sum);  // Output: Sum = 10
    }
}

Complexity Analysis

Time Complexity: O(n)

The loop executes exactly n iterations. Each iteration performs one addition and one increment, both constant-time operations. Total work scales linearly with n.

Space Complexity: O(1)

We use two integer variables (sum and i) regardless of the value of n. No extra memory is needed.

Condition-Driven While Loop — Digit Counting

Intuition

The previous examples used a simple counter to control the loop. But the true power of while loops shines when the number of iterations is unknown beforehand and depends entirely on the data.

Consider counting the digits in a number like 4821. You do not know in advance how many digits it has — you discover this by repeatedly stripping away the last digit. Each time you divide the number by 10 (using integer division), you remove one digit and increment a counter. The loop stops when the number reaches 0, meaning all digits have been stripped.

This is fundamentally different from a counting loop: here, the condition depends on the state of the data (number > 0), not on a pre-set counter reaching a limit. This is the scenario where while loops are the natural and preferred choice over for loops.

Think of it like peeling layers off an onion. You do not count the layers first — you just keep peeling until there is nothing left. The while loop captures this pattern perfectly.

Step-by-Step Explanation

Let's trace counting digits in the number 4821:

Step 1: Initialize number = 4821 and count = 0.

Step 2: Check: Is 4821 > 0? Yes. Divide: number = 4821 / 10 = 482. Increment count to 1.

Step 3: Check: Is 482 > 0? Yes. Divide: number = 482 / 10 = 48. Increment count to 2.

Step 4: Check: Is 48 > 0? Yes. Divide: number = 48 / 10 = 4. Increment count to 3.

Step 5: Check: Is 4 > 0? Yes. Divide: number = 4 / 10 = 0. Increment count to 4.

Step 6: Check: Is 0 > 0? No. Exit loop.

Result: count = 4 (the number 4821 has 4 digits)

While Loop — Counting Digits in 4821 — Watch how integer division by 10 strips away one digit at a time. The loop runs until no digits remain (number reaches 0).

Algorithm

  1. Initialize count = 0
  2. While number > 0:
    a. Divide number by 10 (integer division) to strip the last digit
    b. Increment count by 1
  3. After the loop, count holds the total number of digits

Edge case: If the original number is 0, the loop body never executes and count remains 0. To handle this, you may want to treat 0 as having 1 digit separately.

Code

#include <iostream>
using namespace std;

int countDigits(int number) {
    if (number == 0) return 1;  // Special case: 0 has one digit
    
    int count = 0;
    // Use absolute value to handle negative numbers
    number = abs(number);
    
    while (number > 0) {        // Loop until all digits are stripped
        number /= 10;           // Remove the last digit
        count++;                // Count it
    }
    
    return count;
}

int main() {
    cout << countDigits(4821) << endl;  // Output: 4
    cout << countDigits(0) << endl;     // Output: 1
    cout << countDigits(7) << endl;     // Output: 1
    return 0;
}
def count_digits(number: int) -> int:
    if number == 0:
        return 1  # Special case: 0 has one digit
    
    count = 0
    number = abs(number)  # Handle negative numbers
    
    while number > 0:     # Loop until all digits are stripped
        number //= 10     # Remove the last digit (integer division)
        count += 1        # Count it
    
    return count

print(count_digits(4821))  # Output: 4
print(count_digits(0))     # Output: 1
print(count_digits(7))     # Output: 1
public class DigitCounter {
    public static int countDigits(int number) {
        if (number == 0) return 1;  // Special case: 0 has one digit
        
        int count = 0;
        number = Math.abs(number);  // Handle negative numbers
        
        while (number > 0) {        // Loop until all digits are stripped
            number /= 10;           // Remove the last digit
            count++;                // Count it
        }
        
        return count;
    }
    
    public static void main(String[] args) {
        System.out.println(countDigits(4821));  // Output: 4
        System.out.println(countDigits(0));     // Output: 1
        System.out.println(countDigits(7));     // Output: 1
    }
}

Complexity Analysis

Time Complexity: O(d), where d is the number of digits in the number

The loop runs once per digit. For a number with d digits, that is d iterations. Since d = floor(log₁₀(number)) + 1, this is equivalently O(log n) where n is the numeric value.

Space Complexity: O(1)

We use only two integer variables (count and the mutated number). No additional memory is required.

Common Pitfalls and Patterns

Intuition

Now that we understand the mechanics of while loops, let us examine the most common mistakes beginners make and the important patterns to recognize.

Pitfall 1: Infinite Loops (Forgetting the Update)
If you forget to update the counter or condition variable inside the loop body, the condition never becomes false, and the loop runs forever. This is the single most common while loop bug.

# DANGEROUS — infinite loop!
i = 1
while i <= 5:
    print(i)
    # Missing: i += 1

Pitfall 2: Off-by-One Errors
Using < instead of <= (or vice versa) causes the loop to run one too few or one too many times. Always trace through the boundary case mentally.

i = 1
while i < 5:    # This prints 1, 2, 3, 4 (NOT 5!)
    print(i)
    i += 1

Pitfall 3: Condition Never True
If the initial state already makes the condition false, the loop body never executes. This is not always a bug — it can be intentional (e.g., an empty list).

i = 10
while i <= 5:   # 10 <= 5 is false → body never runs
    print(i)
    i += 1

Pattern: Sentinel-Controlled Loop
Instead of counting, read input until a special value (sentinel) appears:

data = input("Enter a number (or -1 to stop): ")
while data != "-1":
    print(f"You entered: {data}")
    data = input("Enter a number (or -1 to stop): ")

Pattern: Do-While Simulation in Python
Python lacks a do-while loop, but you can simulate it:

while True:
    user_input = input("Enter a positive number: ")
    if int(user_input) > 0:
        break  # Exit when valid input received

Algorithm

While Loop Best Practices:

  1. Always initialize your control variable before the loop
  2. Ensure the loop body modifies something that the condition depends on
  3. Trace through the boundary condition (last iteration) manually to catch off-by-one errors
  4. Use a while loop when the iteration count depends on dynamic data
  5. Use a for loop when the iteration count is known in advance
  6. For do-while behavior in Python, use while True with a break condition
  7. Add safety counters if you are debugging suspected infinite loops:
max_iterations = 10000
count = 0
while condition and count < max_iterations:
    # body
    count += 1

Code

#include <iostream>
using namespace std;

// Do-while loop: guarantees at least one execution
int main() {
    int number;
    
    // Do-while: ask for input until valid
    do {
        cout << "Enter a positive number: ";
        cin >> number;
    } while (number <= 0);  // Repeat if input is not positive
    
    cout << "You entered: " << number << endl;
    
    // Sentinel-controlled loop
    int sum = 0;
    int input;
    cout << "Enter numbers to sum (-1 to stop): ";
    cin >> input;
    
    while (input != -1) {
        sum += input;
        cout << "Enter next number (-1 to stop): ";
        cin >> input;
    }
    
    cout << "Total sum: " << sum << endl;
    return 0;
}
# Do-while simulation in Python
while True:
    number = int(input("Enter a positive number: "))
    if number > 0:
        break  # Exit loop when valid input received

print(f"You entered: {number}")

# Sentinel-controlled loop
total = 0
user_input = int(input("Enter numbers to sum (-1 to stop): "))

while user_input != -1:
    total += user_input
    user_input = int(input("Enter next number (-1 to stop): "))

print(f"Total sum: {total}")
import java.util.Scanner;

public class WhileLoopPatterns {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Do-while: guarantees at least one execution
        int number;
        do {
            System.out.print("Enter a positive number: ");
            number = scanner.nextInt();
        } while (number <= 0);  // Repeat if input is not positive
        
        System.out.println("You entered: " + number);
        
        // Sentinel-controlled loop
        int sum = 0;
        System.out.print("Enter numbers to sum (-1 to stop): ");
        int input = scanner.nextInt();
        
        while (input != -1) {
            sum += input;
            System.out.print("Enter next number (-1 to stop): ");
            input = scanner.nextInt();
        }
        
        System.out.println("Total sum: " + sum);
        scanner.close();
    }
}

Complexity Analysis

Time Complexity: O(n) for sentinel-controlled loops, where n is the number of valid inputs before the sentinel is encountered.

For do-while validation loops, the worst case depends on how many invalid inputs the user provides. In a well-behaved scenario, it is O(1) (user provides valid input on the first try).

Space Complexity: O(1)

All patterns shown use a fixed number of variables regardless of how many iterations occur.