Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: whiledo while, or for. For example, the inner loop can be a while loop while an the outer loop can be a for loop. Of course, they can be the same kind of loops, too.

Both, Java and Python allow to use one loop inside another loop. Following section shows a few examples to illustrate the concept.

Nested

...

while loops

The following program uses a nested for loop to find the prime numbers from 2 to 100:

Code Block
languagejava
titleJava nested loops
// prime numbers from 2 to 100
int i = 2;
while(i < 100){
	int j = 2;
    while(j <= (i / j)){
        if (i % j == 0) break;
        j = j + 1;// or j++;
    }   
    if (j > i/j) System.out.println(i + " is prime");
    i = i + 1; // or i++;    
}
System.out.println("Good bye!");
Code Block
languagepy
titlePython nested loops
# prime numbers from 2 to 100

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " is prime"
   i = i + 1

print "Good bye!"

Nested for loops

You can often use for-loops to make code easier to read. The following code with nested for-loops prints...

...

This journey of the control traveling from the outermost loop, traversing of the inner loop and then back again to the outer for loop continues until the control has covered the entire range, which is 3 times in your case.

Additional example

Consider the timetable that contains seven days, and each day contains 24 time slots. Each time slot is a string, which is empty if there is nothing scheduled for that slot. How can we iterate over all the time slots and print out all our scheduled events?

Code Block
languagejava
titleJava nested loops
 
Code Block
languagepy
titlePython nested loops
# first let's define weekday names
WEEKDAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

# now we iterate over each day in the timetable
for day in timetable:
    # and over each timeslot in each day
    for i, event in enumerate(day):
        if event: # if the slot is not an empty string
            print("%s at %02d:00 -- %s" % (WEEKDAYS[day], i, event))

 

Note that we have two for loops – the inner loop will be executed once for every step in the outer loop’s iteration. Also note that we are using the enumerate function when iterating over the days – because we need both the index of each time slot (so that we can print the hour) and the contents of that slot.

 

You may have noticed that we look up the name of the weekday once for every iteration of the inner loop – but the name only changes once for every iteration of the outer loop. We can make our loop a little more efficient by moving this lookup out of the inner loop, so that we only perform it seven times and not 168 times!

Code Block
languagejava
titleJava nested loops
 
Code Block
languagepy
titlePython nested loops
for day in timetable:
    day_name = WEEKDAYS[day]
    for i, event in enumerate(day):
        if event:
            print("%s at %02d:00 -- %s" % (day_name, i, event))

This doesn’t make much difference when you are looking up a value in a short tuple, but it could make a big difference if it were an expensive, time-consuming calculation and you were iterating over hundreds or thousands of values.