Reputation:
I must produce the following output using only nested for loops:
-----1-----
----333----
---55555---
--7777777--
-999999999-
I cannot use any while or if statements
Here is my code:
public static void printDesign() {
//for loop for the number of lines
for (int i = 1; i <= 9; i++) {
//for loop for the left -
for (int j = 1; j <= 6 - i; j++) {
System.out.print("-");
}
//for loop for #'s
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(i);
}
//for loop for the right -
for (int x = 1; x <= 6 - i; x++) {
System.out.print("-");
}
System.out.println();
}
}
This is what it produces:
-----1-----
----222----
---33333---
--4444444--
-555555555-
66666666666
7777777777777
888888888888888
99999999999999999
How can I get it to only produce the odd numbers?
Upvotes: 3
Views: 8111
Reputation: 1777
for (int i = 1; i <= 9; i += 2) {
for (int j = 0; j < (9 - i) / 2; j++) System.out.print('-');
for (int k = 0; k < i; k++) System.out.print(i);
for (int l = 0; l < (9 - i) / 2; l++) System.out.print('-');
System.out.println();
}
Output:
----1----
---333---
--55555--
-7777777-
999999999
Upvotes: 3
Reputation: 2056
Sounds like a homework assignment. But I'll give you the hint that the key is in the "for(" line.
Upvotes: -1
Reputation: 70939
Your solution is very close to the correct one. Simply change the step of i
in the outer cycle.
Upvotes: 3
Reputation: 41200
Change your first for-loop increment value from 1 to 2.
for (int i = 1; i <= 9; i+=2){}
Upvotes: 2