Skip to main content

Help with Nested Loops

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
4 replies [Last post]
son012189
Offline
Joined: 2011-09-26

Display the following: Using loops

1
21
321
4321
54321

This is my attempt.

Java Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:

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.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mlu909
Offline
Joined: 2011-09-28

Well ,besides ,To fix your code compare it to the following

This code works ....try it out!

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

son012189
Offline
Joined: 2011-09-26

Thank you. I was finally able to get the code to work using the code you gave me.

Here's the solution.

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();

}

}

}

kc1988B
Offline
Joined: 2011-09-27

Instead of using nested for loops, try this:
<code>
for(int i = 1; i <= 5; i++)
switch(i){
case 1: System.out.println(i);
break;
case 2: System.out.println(i + "" + (i-1));
break;
case 3: System.out.println(i+ "" + (i-1) + "" + (i-2));
break;
case 4: System.out.println(i + "" + (i-1)+ "" + (i-2) + "" + (i-3));
break;
case 5: System.out.println(i + "" + (i-1)+ "" + (i-2) + "" + (i-3) + "" + (i-4));
break;
}
</code>

son012189
Offline
Joined: 2011-09-26

Ok, thanks. I will try that. However I think my professor will take off a few points for not using a nested loop.