Program Logic

Unit 7 Index

Nested Loops

Nested Loops

You already know that a loop can be nested inside of a decision statement. You also know that a decision statement can be nested inside a repetition structure. Combining programming techniques is a powerful concept that may be crucial in order to solve a problem. This chapter focuses on Nesting a loop within another loop. Remember, when nesting loops, it is a good idea to give your iterator variables meaningful names.

Code Example

When you need nested loops and you are writing the 5-Step Solution Algorithm, you can code the loops as shown below. Please study the pseudocode on this page.

public Constructor(){
  call createGridOfStars();
}

private method createGridOfStars(){
  declare and initialize int outerLoop it will track iterations of the outer loop
  declare and initialize int innerLoop it will track iterations of the inner loop
  
  WHILE (outerLoop counter is less than 5){

    WHILE (innerLoop counter is less than 5){
      print to the console a "*" 
      increment innerLoop by 1 (innerLoop++)
    }//end of inner while

    print a blank line to the console
    reset innerLoop counter to zero
    increment outerLoop by 1 (outerLoop++)
	
  }//end of outer while

}//end of method

Please study the Java code snippet, which corresponds with the Solution Algorithm above.

/*This is an example of nested looping 
  with while loops.*/

private void createGridOfStars(){
   int outerLoop = 0;
   int innerLoop = 0;
   final String STAR = " * ";

   while(outerLoop < 5){
      while(innerLoop < 5){
         System.out.print(STAR);
         innerLoop++;
      }//end the inner while loop

      System.out.println();
      innerLoop = 0;
      outerLoop++;

   }//end the outer while loop

}//end of method
 *  *  *  *  *
 *  *  *  *  *
 *  *  *  *  *
 *  *  *  *  *
 *  *  *  *  *

The Concept

Here is how nested loops work. We need a loop counting variable for each of the nested while loops in our program. In our example, there are two while loops nested together, therefore, we need two iterator variables. Our output, the star, does not change, which makes it a great candidate for a named constant.

Next, we create the outer loop. The outer loop is the loop that runs first. It is crucial that you declare and initialize your counting variables. Equally as important, we need to change our loop condition. Notice the iterator variable outerLoop is incremented inside of the outer loop.

This outer loop will only run five times, which means all code in it will run five times, even our inner loop!

Now put our inner loop inside of the outer loop. In our example, for every one time the outer loop runs, the inner loop runs five times. Why, because the condition for our inner loop is testing to see if innerLoop which is initialized to zero, is still less than five.

Once the condition becomes false, the code jumps out of the inner loop, but the outer loop still needs to iterate, so the cycle continues until outerLoop is no longer less than five. However, in order keep the inner loop iterating so we have a grid of stars, we need to reset the inner loop counter before the outer loop runs again. Please study the code and code comments below; they are critical to your understanding this concept.


// Adding the inner loop

while (outerLoop < 5) {
  // the outer loop runs five times

  //the inner loop completely inside the outer loop.
  while (innerLoop < 5) {
    // the inner loop runs five times for
    // every one time the outer loop runs,
    // this means the inner loop runs a total of 25 times.
    ...
    innerLoop++;
  }
  print a blank line
  innerLoop = 0; //<-- Reset the inner loop counter
  outerCount++;  // <-- Increment the outer loop counter.
}

The outer loop, prints a blank line after the inner loop completes each iteration. The blank line formats our stars into a grid. Remember, in order to continue running the inner loop through each iteration of the outer loop, you must reset the inner loop iterator variable.

Interactive Live Demo

Below is an interactive demonstration of the nested while loops. Press the “Loop Once” button and see what happens. Press the button multiple times and pay attention to the counter values.

Outer Loop Counter: 0
Inner Loop Counter: 0

We used nested while loops to solve this problem. Remember, when you know the number of times a loop must iterator, a for is a superior option.

Assignment Information

What's next?

This concludes the unit on Repetition Structures. After completing the homework assignments, please study for the final exam.