Java to print number triangle with nested loop

有些话、适合烂在心里 提交于 2020-01-07 09:40:20

问题


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


回答1:


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 +" ");
    }

}



回答2:


Your Program should be -

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

Thanks




回答3:


Set this condition in inner second loop.

for (int j = 1; j <= 7 - i ; j++) 

Edit :

Complete code is

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



回答4:


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



回答5:


This is giving the same output ... Please check

public static void main(String[] args)
    { int c=0;

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

        }  
    }

}



回答6:


Try this :

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

}



来源:https://stackoverflow.com/questions/15463925/java-to-print-number-triangle-with-nested-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!