Java – Try printing only a pyramid of incrementing numbers with lines on the sides using only nested for loops (Java).

Try printing only a pyramid of incrementing numbers with lines on the sides using only nested for loops (Java)…. here is a solution to the problem.

Try printing only a pyramid of incrementing numbers with lines on the sides using only nested for loops (Java).

I’m a beginner in Java.
I’m working on a nested for loop issue… Then the question arises. After researching and trying again, I can’t understand it. It must be solved using nested-only for loops.

That’s what the question wants my code to output :

-----1-----
----333----
---55555---
--7777777--
-999999999-

This is as close as I got :

---------1
-------333
-----55555
---7777777
-999999999

Here is my code :

for (int line = 1; line <= 9; line+=2) {
    for (int j = 1; j <= (-1 * line + 10); j++) {
        System.out.print("-");
    }
    for (int k = 1; k <= line; k++) {
        System.out.print(line);
    }
    System.out.println();
}

Solution

You just need to add another for loop to print on the right side-.
Again, now the first and third loops will be executed half the times

for (int line = 1; line <= 9; line+=2) {
    for (int j = 0; j <= (-1 * line + 10) / 2; j++) {
        System.out.print("-");
    }
    for (int k = 1; k <= line; k++) {
        System.out.print(line);
    }
    for (int j = 0; j <= (-1 * line + 10) / 2; j++) {
        System.out.print("-");
    }
    System.out.println();
}

Related Problems and Solutions