Search this site


 Java for beginners (topic index)  Variables  for (loops)  if  else  logical operators  arrays  objects

Nested for loops

On the previous page, we saw how to create a for loop in Java. This is generally where a single variable cycles over a range of values.

Very often, it's useful to cycle through combinations of two or more variables. For example, we printed out a single times table, but what if we wanted to print out all the times tables, say, between 2 and 12?

One common way to do this is to use a nested loop. That's just a fancy way of saying one loop inside another. So we start with one loop, which goes through all the "times table numbers" in turn that we want to print (in this case, we said between 2 and 12):

for (int timesTableNo = 2; timesTableNo <= 12; timesTableNo++) {
}

Then, inside this loop, we place our other loop that printed the 7 times table. Only this time, we don't want it to print the 7 times table each time— we want it to print the timesTableNo times table each time. So the program looks like this:

for (int timesTableNo = 2; timesTableNo <= 12; timesTableNo++) {
  System.out.println("The " + timesTableNo + " times table:");

  for (int n = 1; n <= 12; n++) {
    int result = n * timesTableNo;
    System.out.println(timesTableNo + " times " + n + " equals " + n);
  }
}

Now, the lines in bold will be run for all combinations of times table number and n. Notice that each times table is also preceded by a "heading" that announces it as "The 2 times table" etc. The line to do that sits only inside the timesTableNo loop, so it only gets run once for every times table, not once for every combination. Try running the program and confirming that it prints all the times tables, for every value between 1 and 12.

Names: inner and outer loop

Because the loop over n is inside the loop over timesTableNo, the n loop would often be called the inner loop, and the timesTableNo loop the outer loop.

Next...

On the next page, we look at if statements, which allow our program to take decisions or check conditions.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.