# Using Nested Loops

• 09-27-2011, 12:28 AM
son012189
Using Nested Loops
Display the following: Using loops
Quote:

1
21
321
4321
54321
This is my attempt.
Code:

public class UsingLoops {
public static void main(String[] args) {
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(" ");
}
System.out.print(line);
for (int j = 1; j >= (-1 * line + 3); j--) {
System.out.print(j + 3);
}
System.out.println();
}
}
}

This is the output that I get:
Quote:

1
24
343
4432
54321
What am I doing wrong? How do I fix my code?
It appears the space aren't showing when I created this thread. There is supposed to be 4 spaces before the first line, 3 spaces before the second line and so on.
• 09-27-2011, 12:45 AM
Fubarable
Re: Using Nested Loops
For one, your second inner loop, the one that creates the numbers to be displayed:

Code:

for (int j = 1; j >= (-1 * line + 3); j--) {
System.out.print(j + 3);
}

needs to be a lot simpler. Think through how you'd do the logic on paper and you'll solve it.
• 09-28-2011, 12:46 AM
son012189
Re: Using Nested Loops
I'm still not sure how to get the program to work with a nested loop. However I do know how to get it work using only one loop.
• 09-28-2011, 01:48 AM
Fubarable
Re: Using Nested Loops
• 09-28-2011, 08:05 PM
son012189
Re: Using Nested Loops
Nevermind, I finally got the code to work. Here's my solution.

Code:

public class UsingLoops {
public static void main(String[] args) {
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(" ");
}
for (int j = line; j >= 1; j--) {
System.out.print(j);
}
System.out.println();
}
}
}

• 09-28-2011, 10:16 PM
Iron Lion
Re: Using Nested Loops
Nitpicky, but you might find it useful to consider that -1 * line can instead be rendered -line.
• 10-02-2011, 05:30 AM
son012189
Re: Using Nested Loops
I see. Thanks for the useful tip.