Reputation: 13
My code for Java I used
System.out.println("* Printing the pattern... *");
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(k + " ");
k++;
}
System.out.println();
}
The output I want is
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Upvotes: 0
Views: 349
Reputation: 135
A different solution (not complete, just to give an idea):
String
array to contain each row - rows = new String[n];
Arrays.fill(rows, "");
for (var col = 0; col < n; col++)
for(var row = col; row < n; row++)
rows[row] += num;
num += 1;
(could be done in above statement using ++
, I prefer it explicit)return String.join("\n", rows);
Alternative: store int in 2d-array rows = new int[n][n];
Upvotes: 0
Reputation: 1319
Your code is unfortunately not correct. Try this simple code where rows is the input parameter:
int rows = 5;
for (int i = 1; i <= rows; i++)
{
int number = i;
for (int j = 1; j <= i; j++)
{
System.out.print(number + " ");
number += (rows - j);
}
System.out.println();
}
If you look at the wanted result:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
you can see that the first element of the row is going from 1 to the given number of rows. The second element equals to first element + the number of rows - 1. The third element is equals to the second element + the number of rows - 2 and so on.
My code implements this simple algorithm.
Upvotes: 4