Quantcast
Channel: Number pattern problem using Java - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 2

Number pattern problem using Java

$
0
0

Got this question in a test.

Display the following number pattern using Java.

User inputs number of rows. For example 3

111232223334

For 5

111112322222333334544444555556

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 < 1; i++) //first row    {        for (j = 0; j < n; j++)         {            myarray[i][j] = i + 1;        }        myarray[i][n] = i + 2;    }    for (i = 1; i < myarray.length; i++)         {        if (i % 2 != 0)    //odd rows           {            j = 1;            myarray[i][0] = i + 2;            while (j <= n)             {                myarray[i][j] = i + 1;                j++;            }            j = 1;        }        if (i % 2 == 0)   //even rows        {            j = 0;            while (j < 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?


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images