Question: question: Design an algorithm and then write a program that prompts the user to enter an integer from 1 to 15 (assume that the user
question: Design an algorithm and then write a program that prompts the user to enter an integer from 1 to 15 (assume that the user always enters a valid integer) and displays a pyramid, as shown in the following sample run:
Enter a number between 1 and 15: 7
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
here is my code, the output has too many spaces between the numbers, how to i change them to 2 spaces like the above.
import java.util.Scanner;
public class DisplayPyramid
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Get maximum rows number from the user
System.out.println("Enter a number between 1 and 15:");
int maxRow = input.nextInt();
//go through the rows from 1 to maxrow
for (int row = 1; row <= maxRow ; row++){
//print space that is maxrow
for(int numberOfSpace = maxRow - row; numberOfSpace >= 1; numberOfSpace-- )
System.out.print(" \t");
//print maxrow to 1
for(int col = row; col >= 1; col--)
System.out.printf(col+"\t");
for(int col = 2; col <= row; col++)
//print column from 2 to maxrow
System.out.print(col+"\t");
//switch to next line
System.out.println();
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
