How to create a Java triangle using number like one by one number

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

Answers (2)

user16320675
user16320675

Reputation: 135

A different solution (not complete, just to give an idea):

  • create a String array to contain each row - rows = new String[n];
  • fill the array with empty strings - Arrays.fill(rows, "");
  • use a loop for columns - for (var col = 0; col < n; col++)
  • with a second loop for rows, starting at the actual column number so we get the triangle - for(var row = col; row < n; row++)
  • add the actual number (variable declared outside loops) to the row - rows[row] += num;
  • increment the number - num += 1; (could be done in above statement using ++, I prefer it explicit)
  • after the loops, join all rows separated by newline (or just print it) - return String.join("\n", rows);

Alternative: store int in 2d-array rows = new int[n][n];

Upvotes: 0

Viktor T&#246;r&#246;k
Viktor T&#246;r&#246;k

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

Related Questions