Reputation: 33
I'm a beginner at Java. I was solving nested for loop questions... Then this question came up. After research and re-tries I couldn't get my head around it. It must be solved using only nested for loops.
This is 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
This 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();
}
Upvotes: 3
Views: 66
Reputation: 1344
You just need to add another for loop to print -
on the right side.
Also now the first and the third loop will execute for half the number of 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();
}
Upvotes: 3