Concepts / Choosing Between Loop Types

Choosing Between Loop Types

Control structures in Java can contain other control structures, and any combination of one inside another is possible.

  • Programming

A Belief Worth Testing

Once you learn that control structures can be placed inside one another, it is tempting to conclude that any arrangement is acceptable. If the language lets you write something, the reasoning goes, then it must also be good style. Keep that belief in mind as you read, because this article examines whether it holds.

What do you think happens?

Can Java place a while loop inside an if statement, and that if statement inside another while loop?

  • No, Java allows only one level of control structure

  • Yes, any combination of one control structure inside another is possible

Reveal answer
Answer:

Yes, any combination of one control structure inside another is possible.

The source states that Java control structures can contain other control structures, and that nesting can continue through several levels. A while loop inside an if statement, inside another while loop, is a valid arrangement.

What Nesting Means

Definition

A control structure is a statement that contains other, simpler statements. When one control structure sits inside another, the inner one is said to be nested inside the outer one. Nesting is a relationship of containment: each structure is a container, and what it holds may be a simple statement or another control structure.

You have already met two familiar combinations. An if statement can be placed inside a loop, and a while loop can be placed inside another while loop. The source makes a broader point, though: any combination of one control structure inside another is possible. Nesting is not restricted to a pair of structures. It can continue through several levels. A while loop inside an if statement, with that if statement inside another while loop, is one such case.

The easiest way to read a deeply nested structure is from the outside in. Start with the outermost container, then move to what it holds, and so on down. Each layer wraps the one beneath it, so the innermost statement is governed by every container around it.

outer while loopif statementinner while loopsimple statementcontainscontainscontains
Which blocks are contained inside which? Read from the top down: the outer while loop contains the if statement, the if statement contains the inner while loop, and the inner while loop contains a simple statement.

Why Nested for Loops Appear Often

Among all the ways to nest control structures, the nested for loop deserves particular attention. The source states that nested for loops arise naturally in many algorithms and that understanding how they work is important. This is not an unusual trick reserved for rare programs. When a problem has two dimensions or two independent counts, a loop inside a loop is often the natural way to express it. Printing a multiplication table is a standard example, because it needs one count for rows and another count for columns.

Tracing a Nested for Loop

The key to reading a nested for loop is remembering that the inner loop is not a one-time event. Each full pass of the outer loop causes the inner loop to start again from its beginning and run through all of its own iterations before control returns to the outer loop. The outer loop therefore controls how many times the whole inner loop runs, and the inner loop controls how many times the body runs within each of those passes.

java
Output
1 2 3 
2 4 6 
Notes on the code
  • The outer loop variable row runs from 1 to 2, so the outer body runs twice.
  • The inner loop variable col runs from 1 to 3 on every outer pass.
  • The println after the inner loop ends each row of the table.

Trace the execution step by step. With row equal to 1, the inner loop runs with col equal to 1, 2, and 3, printing 1, 2, and 3. When the inner loop's condition becomes false, control leaves the inner loop and reaches the println, which ends that line. Then the outer loop's update step runs, row becomes 2, and the inner loop starts again from col equal to 1. It prints 2, 4, and 6, and the inner loop finishes once more before the outer loop's condition is checked and the program ends.

row = 1col = 1col = 2col = 3row = 2col = 1col = 2col = 3enter innercol++col++inner ends, row++enter inner againcol++col++
After the inner loop finishes its last iteration for row 1, what runs next? The inner loop does not end the program. Control returns to the outer loop's update, row becomes 2, and the inner loop restarts from col equal to 1.

Counting Inner Body Executions

Predicting how many times the inner body runs is the central skill here. Because the inner loop runs fully on every outer pass, you can count in two stages. First count how many times the inner body runs in one complete inner loop. Then multiply by the number of outer passes. Each outer pass contributes the same full set of inner iterations.

Worked example

Counting body runs for an outer loop of 3 and an inner loop of 4

An outer loop runs 3 times. On each outer pass, the inner loop runs 4 times. How many times does the inner body execute in total?

  1. 1
    Count one inner loop

    The inner loop runs 4 times on each outer pass, so one complete inner loop executes the inner body 4 times.

  2. 2
    Count the outer passes

    The outer loop runs 3 times, and each pass restarts the inner loop from its beginning.

  3. 3
    Multiply the two counts

    3 outer passes multiplied by 4 inner runs per pass gives 12 total inner-body executions.

Result

The inner body runs 12 times in total.

outer pass 04 inner runs, total 4outer pass 14 inner runs, total 8outer pass 24 inner runs, total 12
If the outer loop runs 3 times and the inner loop runs 4 times per outer pass, how does the total build up? Each outer pass adds 4 inner-body runs to the running total.

What do you think happens?

In the 2 by 3 multiplication table code from the previous part, how many times does the inner println-free body, the print statement, execute in total?

Reveal answer
Answer:

6 times

The outer loop runs 2 times and the inner loop runs 3 times per outer pass. Multiplying 2 by 3 gives 6 executions of the print statement, one for each cell of the table.

When Nesting Becomes Excessive

Java places no limit on how deeply control structures may be nested. The compiler accepts any depth that is syntactically valid, so the real constraint is human. The source explains that, as a practical matter, a program with more than a few levels of nesting is difficult to understand. A reader must keep each enclosing condition in mind while following the code inside it, and each added level increases that burden.

A useful test is to ask whether a reader can follow the code without repeatedly scrolling back to see which enclosing structure governs the current line. When the answer is no, the nesting has likely grown past the point of comfortable reading. The source does not prescribe a fixed numeric limit, so judgment about the specific program is part of the skill.

Mistakes to Avoid

  • Common mistake

    Assuming the inner loop runs only once

    What it looks like

    Reading the multiplication table code and concluding that the inner loop runs a single time for the whole program.

    Why it fails

    Each full pass of the outer loop restarts the inner loop from its beginning, so the inner loop runs completely on every outer pass.

    Do this instead

    Count the inner loop separately on each outer pass, then multiply by the number of outer passes.

  • Common mistake

    Believing that deeper nesting is more acceptable

    What it looks like

    Stacking several structures inside one another because the language allows it.

    Why it fails

    Java's syntax sets no limit on nesting, but a reader must hold every enclosing condition in mind, so each added level makes the code harder to follow.

    Do this instead

    Treat excessive nesting as a readability problem and judge the code by how easily someone can follow it.

  • Common mistake

    Expecting the program to end when the inner loop finishes

    What it looks like

    Assuming that when the inner condition becomes false, the whole program stops.

    Why it fails

    The path leaving the inner loop returns to the outer loop's update step, so the outer loop continues.

    Do this instead

    After the inner loop ends, check the outer loop's update and condition to see what runs next.

Applying the Ideas to a Fresh Problem

EASY

An outer loop runs 5 times, and each pass runs an inner loop 2 times. Without running any code, predict the total number of inner-body executions. Then explain in one sentence why the inner loop restarts on every outer pass.

Hints
  • Count one complete inner loop first.
  • Multiply the inner count by the number of outer passes.
MEDIUM

Describe a situation in which a while loop is nested inside an if statement that is itself nested inside a for loop. Name the outermost and innermost structures, and state which block contains which.

Hints
  • Read the structure from the outside in.
  • Each container holds the structure beneath it.

Key Takeaways

  • A control structure can contain other control structures, and any combination of one inside another is possible, through several levels.
  • Nested for loops arise naturally in many algorithms, such as printing a multiplication table, and the inner loop runs fully on every outer pass.
  • To count inner-body executions, count one complete inner loop, then multiply by the number of outer passes.
  • Java's syntax sets no limit on nesting, but excessive nesting is hard to read, so it should be avoided as a style rule.