The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Two-Dimensional Tables

A two-dimensional table is a table where you choose a row and a column and read the value at the intersection. A multiplication table is a good example. Let's say you wanted to print a multiplication table for the values from 1 to 6.

A good way to start is to write a simple loop that prints the multiples of 2, all on one line.

    int i = 1;
    while (i <= 6) {
      System.out.print (2*i + "   ");
      i = i + 1;
    System.out.println ("");

The first line initializes a variable named i, which is going to act as a counter, or loop variable. As the loop executes, the value of i increases from 1 to 6, and then when i is 7, the loop terminates. Each time through the loop, we print the value 2*i followed by three spaces. Since we are using the print command rather than println, all the output appears on a single line.

As I mentioned in Section 2.4, in some environments the output from print gets stored without being displayed until println is invoked. If the program terminates, and you forget to invoke println, you may never see the stored output.

The output of this program is:

2   4   6   8   10   12

So far, so good. The next step is to encapsulate and generalize.

Last Update: 2011-01-24