Java to print number triangle with nested loop

for-loopjavanested-loops

I am trying to print the following using a nested loop in Java:

1 2 3 4 5 6
   1 2 3 4 5
      1 2 3 4
         1 2 3
            1 2
               1

but it's coming out like the following:

1 2 3 4 5 6
   2 3 4 5 6
      3 4 5 6
         4 5 6
            5 6
               6

Here is my code:

for (int i = 1; i <= 6; i++) {
    for (int j = 1; j < i; j++) 
    {
        System.out.print("  ");
    }
    for (int j = i; j <= 6; j++) 
    {
    System.out.print(j + " ");
    }
    System.out.println();
}

Any help would be appreciated. Thanks

Best Answer

int n = 7;

for (int i = 1; i <= n; i++) {

    for (int j = 1; j < i; j++) {
        System.out.println(" ");
    } 
    for (int j = i; j <= 6; j++) {              
       System.out.println(j +" ");
    }

}