Ahad Sheriff - 1 month ago 9

Java Question

I have to write a program that takes a size value and turns it into a right triangle (made up of

`#`

`#`

#

###

#####

#

###

#####

#######

The first triangle is of size 1.

The second triangle is of size 4.

The third triangle is of size 6.

Notice that the the number of characters per each line in a given triangle is always odd.

Also notice that the height of each triangle at the largest point can be calculated by

`size/2 + 1`

I have attempted this problem, but I am stuck figuring out how I can display the correct number of

`#`

Here is my own code:

`public class triangle {`

public static void drawTriangle(int size) {

int column = (size/2) + 1;

for (int i = 0; i <= column; i++) {

for (int j = size; j >= 0; j--) {

if (i <= j) {

System.out.print(" ");

}

else {

System.out.print("#");

}

}

System.out.println();

}

}

public static void main(String[] args) {

drawTriangle(1);

drawTriangle(4);

drawTriangle(6);

}

}

And here is the output from my code:

`#`

#

##

###

#

##

###

####

As you can see I have arranged the triangles in the proper way, and have gotten the height of each triangle to be the way it supposed to. I just have no idea how I can get the correct number off characters on each line...

I have tried several things including changing my first for loop from:

`for (int i = 0; i <= column; i++)`

to

`for (int i = 1; i <= column; i+=2)`

Which filters out the even numbered rows, but fails to address the other parameters such as height of each triangle, and additional rows. Here is the output for my changes:

`#`

#

###

#

###

Any help is appreciated, thanks.

Answer

Here you go. I tried to name the variables in a way that helped you understand the algorithm better.

```
public static void drawTriangle(int size) {
int iterations = (size/2) + 1;
int lineLen = 1;
for (int i = 0; i < iterations; i++) {
for (int spaces = 0; spaces <= size - lineLen; spaces++) {
System.out.print(" ");
}
for (int hashes = 0; hashes < lineLen; hashes++) {
System.out.print("#");
}
System.out.println();
lineLen += 2;
}
System.out.println();
}
```

As Code-Apprentice said, it makes sense for there to be one main `for`

loop to display each row. Then, in order to display the correct number of spaces and hashes, I used two nested `for`

loops. One key thing to note: I increment `lineLen`

by 2 each time through the main loop, in order to cound the odd number of hashes in each line.

Source (Stackoverflow)

Comments