patternjavaMinor
Number pattern problem using Java
Viewed 0 times
problemnumberjavausingpattern
Problem
Got this question in a test.
Display the following number pattern using Java.
User inputs number of rows. For example 3
For 5
and so on.
This is the solution I came up with:
Is there a better way of solving this problem with only one
Display the following number pattern using Java.
User inputs number of rows. For example 3
1112
3222
3334For 5
111112
322222
333334
544444
555556and 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?Solution
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):
If you need to store the numbers to be used elsewhere, then yes, put them into an array.
// note that method namess should begin with a lower-case letter
public static void numberPattern(int rows) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < rows + 1; col++) {
int number = 0;
if (row % 2 == 0) {
number = col < 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.
Code Snippets
// note that method namess should begin with a lower-case letter
public static void numberPattern(int rows) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < rows + 1; col++) {
int number = 0;
if (row % 2 == 0) {
number = col < rows ? row + 1 : row + 2;
} else {
number = col == 0 ? row + 2 : row + 1;
}
System.out.print(number);
}
System.out.println();
}
}Context
StackExchange Code Review Q#45701, answer score: 5
Revisions (0)
No revisions yet.