CrypticZero - 1 year ago 61
Java Question

# Making a single number per line pyramid using nested loop and trying to center it

I have to create a number pyramid using nested loops for homework. I am very new to nested loops and am still not quite clear on how they work completely. My objective is to make this pyramid using nested loops:

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

however I have only been able to get this:

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

I think I am on the right track but I am not sure where to go from here.
Here is the code I currently have:

``````public class NumberPyramid

{
public static void main(String [] args)
{
for(int i=1; i<=9; i+=2)
{
for (int j = 11; j > i; j--)
{
System.out.print("-");
}
for(int j=1; j<=i; j++)
{
System.out.print(i);
}
for (int j = 1; j < i; j++)
{
System.out.print("-");
}
System.out.println();
}
}
}
``````

The part of printing the numbers in the center is correct. Printing the `-` before and after the numbers is incorrect.

Notice that for any row, the number of `-` before and after the numbers should be the same. How many `-` to print for a number?

• For `1`, print 5 `-` before and after.
• For `3`, print 4 `-` before and after.
• For `5`, print 3 `-` before and after.

That's `(11 - i) / 2`. Put this loop before and after the center line and you're done.

``````for (int j = 0; j < (11 - i) / 2; j++) {
System.out.print("-");
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download