Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("");
}
like image 659
Kerry G Avatar asked Jul 10 '12 08:07

Kerry G


People also ask

How do you make a for loop triangle in Java?

First, we see that we need to print 4 spaces for the first row and, as we get down the triangle, we need 3 spaces, 2 spaces, 1 space, and no spaces at all for the last row. Generalizing, we need to print N – r spaces for each row.

How do you write a triangle in Java?

To draw a triangle in Java, you can utilize a “while” or “for” loop. Java supports the loop statements that help to draw different shapes like triangles, patterns, and others. You can draw any type of shape by using the loop statements.

What is Floyd's triangle in Java?

Floyd's triangle, named after Robert Floyd, is a right-angled triangle, which is made using natural numbers. It starts at 1 and consecutively selects the next greater number in the sequence.


1 Answers

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.

like image 163
Simeon Visser Avatar answered Oct 03 '22 17:10

Simeon Visser