Creating a triangle with for loops

2019-01-04 02:04发布

I don't seem to be able to find the answer to this-

I need to draw a simple triangle using for loops.

     *  
    ***
   *****
  *******
 *********

I can make a half triangle, but I don't know how to add to my current loop to form a full triangle.

 *
 **
 ***
 ****
 *****



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

Thanks-

11条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-04 02:07

Try this one in Java

for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}
查看更多
小情绪 Triste *
3楼-- · 2019-01-04 02:10

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-04 02:10

Homework question? Well you can modify your original 'right triangle' code to generate an inverted 'right triangle' with spaces So that'll be like

for(i=0; i<6; i++)
{
for(j=6; j>=(6-i); j--)
{
   print(" ");
}
for(x=0; x<=((2*i)+1); x++)
{
   print("*");
}
print("\n");
}
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-04 02:10

This lets you have a little more control and an easier time making it:

public static int biggestoddnum = 31;

public static void main(String[] args) {
    for (int i=1; i<biggestoddnum; i += 2)
    {
        for (int k=0; k < ((biggestoddnum / 2) - i / 2); k++)
        {
            System.out.print(" ");
        }
        for (int j=0; j<i; j++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }
}

Just change public static int biggestoddnum's value to whatever odd number you want it to be, and the for(int k...) has been tested to work.

查看更多
Anthone
6楼-- · 2019-01-04 02:12

First think of a solution without code. The idea is to print an odd number of *, increasing by line. Then center the * by using spaces. Knowing the max number of * in the last line, will give you the initial number of spaces to center the first *. Now write it in code.

查看更多
Viruses.
7楼-- · 2019-01-04 02:16

Well, there will be two sequences size-n for spaces and (2*(n+1)) -1 for stars. Here you go.

public static void main(String[] args) {
    String template = "***************************";
    int size = (template.length()/2);
    for(int n=0;n<size;n++){
        System.out.print(template.substring(0,size-n).replace('*',' '));
        System.out.println(template.substring(0,((2*(n+1)) -1)));
    }
}
查看更多
登录 后发表回答