Incremental Java
Adding Loops to a Class

Adding a Nested Loop to Rectangle

We wrote this code in the lesson on nested loops.
public void printRectangle()
{
   for ( int row = 0 ; row < height ; row++ )
   {
      // PRINT a row
      for ( int col = 0 ; col < width ; col++ )
      {
         System.out.print( "*" ) ;
      }
      // PRINT newline
      System.out.println( "" ) ;
   }
}
Let's try a simple variation. We'll print it sideways. Thus, we have width rows, and height columns. All we have to do is to swap width and height, and we're done!
public void printRectangle()
{
   for ( int row = 0 ; row < width ; row++ )
   {
      // PRINT a row
      for ( int col = 0 ; col < height ; col++ )
      {
         System.out.print( "*" ) ;
      }
      // PRINT newline
      System.out.println( "" ) ;
   }
}

A Challenge

Here's a challenging problem. Suppose width is 3 and height is 5. Write a method to print:
  012
0 ***
1 ***
2 ***
3 ***
4 ***
Your method should work for any valid width or height. We'll explain how to do this below. For now, try to figure out the code, then trace it until you're convinced it works correctly.

Breaking it Up

Although it's not obvious, we want to break the code up into two parts. We want to print:
  012
and then print
0 ***
1 ***
2 ***
3 ***
4 ***
Let's work on printing the first part.

Printing the Column Headings