# Upside down Triangle pattern

• 06-06-2011, 04:37 AM
JayP
Upside down Triangle pattern
Hi Sorry if this is something that is often posted but I don't understand why the way I did it doesn't work and I'd like to find out why it doesn't.

The first triangle i did started as such
*
**
***...

This time I'd like to switch it upside down as follows
***
**
*

I did this by using the loop the opposite as I did with the first and instead of having j = 0 and incrementing it, i made j = n and decremented j.

Code:

```          // loop N times, one for each row         for (int i = n; i <= n; i--) {             // print j periods             for (int j = i; j <= i; j--)                 System.out.print("*");             // print a new line             System.out.println();                 }```
But it rolls infinitely... :S

Any help is greatly appreciated!
• 06-06-2011, 04:53 AM
Junky
Assume i = 1
You assign the value of i to j, j is 1.
Is j <= i? Is 1 less than or equal to 1? Yes.
Decrement j, j is now 0;
Is j <= i? Is 0 less than or equal to 1? Yes.
Decrement j, j is now -1;
Is j <= i? Is -1 less than or equal to 1? Yes.
etc

Questions about these star shape programs are always popping up on forums. My advice always is to write another method which takes 2 parameters: the character to be printed on a single line and the number of times it should be printed. Then back in your main method you have a loop that iterates "lines" number of times calling the print method. Now all you have to do is work out the algorithm for how many *'s (and possibly spaces) need to be printed on wach line.
• 06-06-2011, 04:53 AM
airowe
Deconstruct your inner for loop.
• 06-06-2011, 05:00 AM
JayP
What do you mean deconstruct my inner loop?
• 06-06-2011, 05:02 AM
airowe
Quote:

Originally Posted by JayP
What do you mean deconstruct my inner loop?

See Junky's post.

You've setup an infinite loop with the j <= -1 condition.
• 06-06-2011, 05:10 AM
JayP
Why is one of the i's ever be -1? if i = n, and j = i? I'm a little confused.
• 06-06-2011, 05:18 AM
JayP
I also get an infinite loop when I change the parameter to j>=i.
• 06-06-2011, 05:24 AM
JayP
Oh, I see, since j will always be bellow i. So is my entire methodology wrong by using decrements to trying to invert the triangle?
• 06-06-2011, 05:25 AM
Junky
It is because your logic is wrong and you are just guessing. That does not work when it comes to programming. Walk away from the computer, grab a pencil and some paper, write down how many stars appear on each line. Do this for 3 rows, 4 rows, 5 rows etc. Then see if a pattern emerges. Once you have done that you can write the code.

Also did you ignore my advice about writing a separate method? If you do write this method you should find writing the code much easier. Plus it can be used for all such programs.
• 06-06-2011, 05:46 AM
JayP
Figured it out, thanks.