Help with a basic Java program?
I know it’s something with foreloops but I have no idea how to do this.
I use something called SavitchIn, which allows for simple user input.
1.Write a program that ask the user to enter the size of a triangle to print out
(an integer from 1 to 50) then print the triangle by printing a series of lines with
asterisks. The first line will have one asterisk, the next two, etc., each line having
one more asterisk than the previous line up to the number entered by the user; on the
next line print on less asterisk and continue by decreasing the number of asterisks by
one for each successive line until one asterisk is printed. Hint: use nested loops; the
outside loop controls the number of lines to print and the inside loop controls the
number of asterisk to print on a line. For example, if the users enters 5 output is
*
**
***
****
*****
****
***
**
*
*
Observing members:
0
Composing members:
0
2 Answers
just a guide, don’t know java
correct the syntax and stuff and this should be your loop.
INPUT=B
for(A=1; A=<B; A=A+1){
for(a=A; a=>0; a=a-1){
print/echo/say ”*”;
}
print linebreak/</br>/
}
for(A=B; A=>0; A=A-1){
for(a=A; a=>0; a=a-1){
print/echo/say ”*”;
}
print linebreak/</br>/
}
The best way to approach a problem like this is to think about what each loop will do:
1. Print out a number of lines of asterisks.
2. Print out a number of asterisks for every line.
The statements above are clearly loops because they are doing something repeatedly, and they clearly indicate for loops because the number of iterations is known (5 in your example). The outer loop (#1 above) would look something like this:
for (int i = 0; i < num * 2; i ++) { ... }
And the inner loop (#2 above) would look something like this:
for (int j = 0; j < asterisk_count; j ++) { ... }
Now throw in the print statements. The code would look like this:
for (int i = 0; i < num * 2; i ++) {
if (i > num)
asterisk_count = num – (i % num);
else
asterisk_count = i + 1;
for (int j = 0; j < asterisk_count; j ++) {
print ”*”;
}
print ”\r\n”;
}
First loop: loop num * 2 number of times because you want to print out twice the number of lines as the number the user entered. In your example above, the user entered 5 and the program printed 10 lines. I noticed there’s an extra single asterisk line at the end. To get rid of that, you’d use (num * 2) – 1.
Second loop: Print the number of asterisks. asterisk_count
will be set to 1 thru 5 for the first 5 iterations, then 5 to 1 for the next 5 iterations.
This solution only uses one set of nested for loops while @Zyx‘s answer uses two sets of two.
Answer this question