# Integer pyramid 1-15

Printable View

• October 26th, 2013, 04:07 AM
CruelCoin
Integer pyramid 1-15
Hi all.

Am almost there with the problem below.

I need to print an integer pyramid between 1 and 15, but when i get above 10 (11 to 15) i have a spacing problem and not sure how to fix this.

Any and all advice is welcome

Code Java:

```import java.util.Scanner; class Q5 { public static void main (String [] Args) { Scanner input = new Scanner(System.in);   System.out.print("Enter the number of lines: "); int numberOfLines = input.nextInt();   if ((numberOfLines < 1) || (numberOfLines > 15)) { System.out.println("You must enter a number from 1 to 15"); System.exit(0); }   for (int row = 1; row <= numberOfLines; row++) { for (int column = 1; column <= numberOfLines - row; column++) { System.out.print(" "); } for (int num = row; num >= 1; num--) { System.out.print(" " + num); } for (int num = 2; num <= row; num++) { System.out.print(" " + num); }   System.out.println(""); } input.close(); } }```
• October 26th, 2013, 05:40 AM
Norm
Re: Integer pyramid 1-15
Quote:

i have a spacing problem
Please post the output showing the problem and add some comments or examples showing what you want the output to look like.
• October 26th, 2013, 06:49 AM
GregBrannon
Re: Integer pyramid 1-15
I tend to attack these kind of problems differently - not better, necessarily - by generalizing the steps and using simple math where possible:

- calculate the leading spaces
- print the spaces
- print the characters

Looking at your problems, I came up with this generalization:

// each line begins with 2 spaces * total lines to be printed less
// 2 spaces * the current row being printed

For the above, if 15 lines are to be printed, 28 leading spaces will be printed for line 1, and 0 leading spaces will be printed for line 15. As you've already discovered, it's a bit more complicated than that, so the rest of my generalization is:

// if the total number of lines to be printed is greater than 9,
// an extra space must be added to the single-digit lines for each
// of the double-digit lines

// if the current row being printed is > 9 and < the total number of
// lines, reduce leading spaces by 1 for each row > 9 except the last

// print the leading spaces

// print the required numbers

// add a linefeed