Using Looping Structures

What Are Looping Structures?

Loops allow a program to execute a block of code multiple times.

They can be classified into counted loops (fixed iterations) and conditional loops (executed based on conditions).

Types of Loops in Python and Java

Loop Type Description Python Java
Counted Loop Executes a fixed number of iterations based on a counter. for i in range(n): for (int i = 0; i < n; i++) { }
Pre-Condition Loop Checks the condition before each iteration; may execute zero times if condition false. while condition: while (condition) { }
Post-Condition Loop Executes the body once before checking the condition; guarantees at least one execution. Simulated via while True and break do { } while (condition);

Example: Using Loops

Python: Counted Loop

Prints numbers 0–4 using a fixed-iteration for loop (0-based).

# Print numbers 0 to 4 (counted loop)
for i in range(5):
    print("Number:", i)

Python: Pre-Condition Loop

Repeats while the condition remains true; may run zero times if the condition starts false.

num = 0
while num < 5:
    print("Current Number:", num)
    num += 1

Python: Post-Condition (Simulated)

Guarantees the body runs at least once using while True and a break after checking the condition.

count = 0
while True:
    print("Body runs at least once; count =", count)
    count += 1
    if count < 3:   # condition checked after the body
        continue
    break

Java: Counted Loop

Uses a for loop with initialiser, condition, and increment.

public class LoopExample {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("Number: " + i);
        }
    }
}

Java: Pre-Condition Loop

Checks the condition before each iteration; may not run at all if false initially.

public class WhileLoopExample {
    public static void main(String[] args) {
        int num = 0;
        while (num < 5) {
            System.out.println("Current Number: " + num);
            num++;
        }
    }
}

Java: Post-Condition (do…while)

Executes the body once, then checks the condition to repeat or stop.

public class DoWhileDemo {
    public static void main(String[] args) {
        int num = 0;
        do {
            System.out.println("Current Number: " + num);
            num++;
        } while (num < 5);
    }
}

Using Boolean and Relational Operators in Loops

  • Multiple Conditions: Python: while x > 5 and y < 10:; Java: while (x > 5 && y < 10) { }
  • Boundary Checks: Python: for i in range(1, 6):; Java: for (int i = 1; i <= 5; i++) { }

Avoiding Common Loop Errors

Infinite Loops

Error: The loop condition never becomes false (e.g. missing an increment), so the loop runs forever.

Fix: Update the loop variable or add a clear exit (break) so the condition eventually fails.

i = 0
while i < 5:
    print(i)
    # BUG: missing i += 1 → condition never changes
i = 0
while i < 5:
    print(i)
    i += 1  # FIX: update loop variable
int i = 0;
while (i < 5) {
    System.out.println(i);
    // BUG: missing i++ → condition never changes
}
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++; // FIX: update loop variable
}

Off-by-One Errors

Error: Using the wrong bound (< vs <=) or range end means you run one time too few or too many.

Fix: State the intended set of values first (e.g. “1 to 5 inclusive”) and pick bounds/ranges that match.

# Intended: print 1..5 inclusive
for i in range(1, 5):  # BUG: stops before 5
    print(i)
# Correct: end is exclusive, so use 6
for i in range(1, 6):
    print(i)
// Intended: print 1..5 inclusive
for (int i = 1; i < 5; i++) { // BUG: prints 1..4
    System.out.println(i);
}
// Correct bound: <= 5
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Misplaced continue/break

Error: Using break when you meant continue (or vice versa) changes control flow—either stopping the loop too early or skipping needed work.

Fix: Use continue to skip just the current iteration; use break to exit the loop entirely.

# Intended: sum positives, skip negatives
total = 0
nums = [3, -2, 5, -1]

for n in nums:
    if n < 0:
        break          # BUG: exits loop on first negative
    total += n

print("total =", total)
# Use 'continue' to skip just the negative values
total = 0
nums = [3, -2, 5, -1]

for n in nums:
    if n < 0:
        continue
    total += n

print("total =", total)
// Intended: sum positives, skip negatives
int total = 0;
int[] nums = {3, -2, 5, -1};

for (int n : nums) {
    if (n < 0) {
        break;      // BUG: exits loop on first negative
    }
    total += n;
}

System.out.println("total = " + total);
// Use 'continue' to skip just the negative values
int total = 0;
int[] nums = {3, -2, 5, -1};

for (int n : nums) {
    if (n < 0) {
        continue;
    }
    total += n;
}

System.out.println("total = " + total);

 Key Takeaways

  • Looping structures enable repeated code execution through for and while loops.
  • Counted loops (for) suit fixed iterations, while conditional loops (while) depend on runtime conditions.
  • Post-condition loops run the body at least once (Java do…while; Python via while True + break).
  • Prevent errors by verifying loop bounds, ensuring termination, and judicious use of break and continue.