Doing some homework in my CSC 2310 class and I can’t figure out this one problem… it reads:
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 ‘*’. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
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) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can’t figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print
i*characters on a single line, so you just need:Hence you will have:
Or equivalently,
EDIT Using only
whileloops:So to break it down:
We have an outer loop that loops from
i = 100downwards toi = 1.Inside this outer
whileloop, we have another loop that loops from0toi - 1. So, on the first iteration, this would be from 0-99(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a
*character. But we do thisitimes (because it’s a loop), so the first time we have 100
*s, then 99, then 98 etc. (asyou can see from the point above).
Hence, the triangle pattern emerges.