last time i was on here, the only question i needed help with in my computer science homework involved making a right triangle on 100 lines, here was the code for that:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
}
}
well now he’s asked us to do the inverse. here’s the actual question:
“Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 ‘‘, the second line, 99
‘’… the last line, only one ‘*’. Using for loop for this problem.
Name the program as PrintTriangle.java”
*****
****
***
**
*
i’m sure it’s something simple but everything i’ve tried up to this point has flopped or only created 1 space at a time. any suggestions or help would be greatly appreciated! thank you in advance!
OK, first take a look on both the problems. How would you relate them.
Since the second problem is the reverse of the first, so what you did first in your first code, you need to do that last in this next problem..
So, your loop should actually work backwards where it ended in the below code.
So, think what you need to do to make this loop work backwards.
Hint: –
Decrementing from 100 to 0 is backwards
Also, in your above pattern you see that you need to first print
spacesbefore actually printing yourcharactersSo, that too you need to consider.So, here you have to actually print two different characters: –
Spaces, followed by,*'s.Here’s the pattern: –
max(100 in your case)i) has (i) number ofspaces(Row 0 has 0 space, Row 1 has 1 space)n - i) number ofstars(Row 0 has 100 stars, Row 1 has 99 stars)So, you can see that you actually need
twoloops here.Analyze what all I said, and come up with some code. Try it out.