Creating a triangle with for loops

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

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));

First of all, you need to make sure you're producing the correct number of * symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:

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

As you can see, this causes i to start at 1 and increase by 2 at each step as long is it is smaller than 10 (i.e., 1, 3, 5, 7, 9). This gives us the correct number of * symbols. We then need to fix the indentation level per line. This can be done as follows:

for (int i=1; i<10; i += 2)
{
    for (int k=0; k < (4 - i / 2); k++)
    {
        System.out.print(" ");
    }
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

Before printing the * symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k variable is for. We can see that k iterates over the values 4, 3, 2, 1 and 0 when ì is 1,3, 5, 7 and 9. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.


I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.

Let's think about writing a method to print a single line, telling the method which number line it is:

public void printTriangleLine(int rowNumber) {
    // we have to work out what to put here
}

We have to print some number of spaces, then some number of stars.

Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.

Let's invent a method that prints the rows of characters for us, and use it:

public void printTriangleLine(int rowNumber) {
    printSequence(" ", 5 - rowNumber);
    printSequence("*", 2 * rowNumber + 1);
    System.out.println(); 
}

That won't compile until we actually write printSequence(), so let's do that:

public void printSequence(String s, int repeats) {
    for(int i=0; i<repeats; i++) {
        System.out.print(s);
    }
}

Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()

public static void main(String [] args) {
    printSequence("a",3);
    System.out.println();
    printTriangleLine(2);
}

... run it and verify (with your eyes) that it outputs:

aaa
   *****

When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:

assertEquals("   *****", TriangleDrawer.triangleLine(2));
assertEquals("     *", TriangleDrawer.triangleLine(0))

Now we have the pieces we need to draw a triangle.

public void drawTriangle() {
    for(int i=0; i<5; i++) {
        printTriangleLine(i);
    }
}

The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.

For extra credit:

  • adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use System.out.print(drawTriangle())
  • adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call drawTriangle(3) or drawTriangle(5)
  • make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().

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.


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();
}