The Nested loop

4.5 The Nested loop

In Java, one loop may be used inside another loop. For example, here are programs that nests for loops to display patterns:
/**
 *  This program displays a rectangular pattern
 *  of stars.
 */
public class RectangularPattern
{
   public static void main(String[] args)
   {
      final int MAXROWS = 4,
                MAXCOLS = 5;

      for (int i = 1; i <= MAXROWS; i++)
      {
         for (int j = 1; j <= MAXCOLS; j++)
         {
            System.out.print("*");
         }

         System.out.println();
      }
   }
}
Output :
*****
*****
*****
*****

Example 2
/**
 *  This program displays a right angular triangle pattern.
 */
public class TrianglePattern
{
   public static void main(String[] args)
   {
      final int SIZE = 6;

      for (int i = 1; i <= SIZE; i++)
      {
         for (int j = 1; j <= i; j++)
         {
            System.out.print("*");
         }

         System.out.println();
      }
   }
}
Output :
*
**
***
****
*****
******

No comments:

Post a Comment

Pages