Number pattern problem using Java Got this question in a test.


  Display the following number pattern using Java.
  
  User inputs number of rows. For example 3

1112
3222
3334

  
  For 5

111112
322222
333334
544444
555556

  
  and so on.


This is the solution I came up with:

   public static void NumberPattern(int n) {

    int myarray[][] = new int[n][n + 1];
    int i;
    int j;
    for (i = 0; i &lt; 1; i++) //first row
    {
        for (j = 0; j &lt; n; j++) 
        {
            myarray[i][j] = i + 1;
        }
        myarray[i][n] = i + 2;
    }
    for (i = 1; i &lt; myarray.length; i++)  
       {
        if (i % 2 != 0)    //odd rows
           {
            j = 1;
            myarray[i][0] = i + 2;
            while (j &lt;= n)
             {
                myarray[i][j] = i + 1;
                j++;
            }
            j = 1;
        }
        if (i % 2 == 0)   //even rows
        {
            j = 0;
            while (j &lt; n) {
                myarray[i][j] = i + 1;
                j++;
            }
            myarray[i][n] = i + 2;
            j = 0;
        }
    }
    printArray(myarray);

}
 public static void printArray(int n[][])
  {
    System.out.println("The Pattern is:");

    for (int[] array : n) {
        for (int v : array) {
            System.out.print("  " + v);
        }
        System.out.println();
    }
  }


Is there a better way of solving this problem with only one for loop?
Since all you've been asked is to display output, a single simple nesting of two for loops without arrays should work just fine. Note that in all cases, you know in advance prior to performing a loop how many times the loop will iterate, and in this situation a for loop is cleaner than a while loop (though of course both would work):

// note that method namess should begin with a lower-case letter
public static void numberPattern(int rows) {
  for (int row = 0; row &lt; rows; row++) {
     for (int col = 0; col &lt; rows + 1; col++) {
        int number = 0;
        if (row % 2 == 0) {
           number = col &lt; rows ? row + 1 : row + 2;
        } else {
           number = col == 0 ? row + 2 : row + 1;
        }
        System.out.print(number);
     }
     System.out.println();
  }
}


If you need to store the numbers to be used elsewhere, then yes, put them into an array.