Nesting one loop inside another lets your program work across the rows and the columns at the same time, and that is how you print the multiplication tables, the number grids, the pyramids and the checkerboards. The pattern is always the same. The outer loop chooses a row and the inner loop fills it.
The previous lesson in this module covered "When Do break and continue Matter in Loop Control?", and this lesson is the last one in the Java if-else and Loops module.
How do you print a multiplication table?
A single loop is enough for one column of a table. The value that you multiply by changes on every pass, so the loop counter does the double duty as the multiplier.
public class MultiplicationTable {
public static void main(String[] args) {
int table = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(table + " x " + i + " = " + (table * i));
}
}
}The output runs from one to ten.
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70How do you build a grid of the values?
You wrap that loop in another one, and each pass of the outer loop becomes a row, with the inner loop producing the columns of that row.
public class ProductGrid {
public static void main(String[] args) {
int size = 4;
for (int row = 1; row <= size; row++) {
StringBuilder line = new StringBuilder();
for (int col = 1; col <= size; col++) {
line.append(String.format("%4d", row * col));
}
System.out.println(line);
}
}
}The output is a four by four grid of the products, padded so that the columns line up.
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16Two details do the work here. The inner loop appends to a StringBuilder instead of printing, because printing inside the inner loop would break the line after every single value. And the String.format("%4d", ...) pads each number to a fixed width, and that is what keeps the columns vertical.
And notice how the outer loop variable is still readable inside the inner loop. That is the mechanism behind most of the grid patterns. The row index decides what the columns contain, so a cell can depend on both its row and its column. Whenever you are printing a shape, you ask what each cell should look like in terms of its row and column number, and the two loops fall out of that answer.
How do you print a centred pyramid?
A pyramid needs three ingredients. There are some leading spaces to centre the row, and then the characters themselves. The number of the spaces shrinks as the row number grows, and the number of the characters grows with it.
public class Pyramid {
public static void main(String[] args) {
int rows = 5;
for (int row = 1; row <= rows; row++) {
StringBuilder line = new StringBuilder();
for (int space = 0; space < rows - row; space++) {
line.append(' ');
}
for (int star = 0; star < 2 * row - 1; star++) {
line.append('*');
}
System.out.println(line);
}
}
}The output is a centred pyramid.
*
***
*****
*******
*********And notice the shape of the formulas. There are the rows minus the row spaces, and there are two times the row minus one characters. Working out the two numbers first and then writing the loops is much easier than fiddling with the output until it looks right.
How does a checkerboard pattern work?
A checkerboard is a grid where the character depends on the sum of the row and the column indexes. When that sum is even you get one character, and when it is odd you get the other one.
public class Checkerboard {
public static void main(String[] args) {
int size = 6;
for (int row = 0; row < size; row++) {
StringBuilder line = new StringBuilder();
for (int col = 0; col < size; col++) {
line.append((row + col) % 2 == 0 ? "X " : "o ");
}
System.out.println(line);
}
}
}The output alternates on every row.
X o X o X o
o X o X o X
X o X o X o
o X o X o X
X o X o X o
o X o X o XAnd the parity of the row plus the column is what flips the character. Because each row starts on the opposite parity to the one above, the pattern alternates automatically. The same trick draws a chess board or any two-colour grid.
What goes wrong when you nest the loops?
The nested loops multiply their work. Two loops that each run a hundred times run the inner body ten thousand times, and three levels of nesting turn that into a million. Before you write a third level, you check whether a flat loop with an index would do the same work more cheaply.
public class GridStatistics {
public static void main(String[] args) {
int size = 5;
int sum = 0;
for (int row = 1; row <= size; row++) {
for (int col = 1; col < size; col++) {
sum += row * col;
}
}
System.out.println("cells: " + (size * size));
System.out.println("sum of products: " + sum);
}
}The output confirms the cell count and the total.
cells: 25
sum of products: 225And the inner body ran 25 times because the outer loop ran 5 times and the inner loop ran 5 times each. The same idea matters when you break out of the nested loops. A plain break only ends the inner loop, so the outer loop keeps starting the new rows. You use a label when you mean to leave both of them.
And there is a second trap in the nested loops that has nothing to do with the performance. It is the same variable name used for both of the counters. If you write the int i in the outer loop and the int i in the inner one then the compiler rejects it, because the inner declaration would hide the outer one and the outer loop could no longer advance. You use different names, or you declare the counters in the for headers where each one has its own scope.
Summary
- The outer loop picks the row and the inner loop fills it, so you build the row into a string and you print it once the inner loop finishes.
- You use the
String.formatwith a width to line the columns up vertically. - You work out the formula for each part of the pattern first, such as the rows minus the row spaces or the two times the row minus one characters.
- The patterns that alternate rely on the parity of the row plus the column indexes.
- The nested loops multiply the work, so a third level of nesting deserves a second look.
- A break inside the inner loop leaves only that loop, and you label the outer one when you need to leave both of them.
Try it yourself: print a right-aligned triangle of the stars with five rows, then the same triangle pointing to the left, and then a diamond that is made of four of the nested shapes one after the other. Underneath each one, print the number of the characters that you actually output so that you can check the shape is what you intended. Finally, change your inner loop to stop at the row instead of at the size, and describe in one sentence how the output changes and why the total number of the characters shrinks.