**5.17 (Display pyramid) Write a program that prompts the user to enter
an integer from 1 to 15 and displays a pyramid, as shown in the
following sample run:
Enter the number of lines: 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
Using four loops, one to loop through the line, one to print spaces and two other to print numbers, decreamentally and inecrementally.
|line number|number of 2-spaces|
1 1 | (7-1)
2 1 2 2 | (7-2)
3 2 1 2 3 3 | (7-3)
4 3 2 1 2 3 4 4 | (7-4)
5 4 3 2 1 2 3 4 5 5 | (7-5)
6 5 4 3 2 1 2 3 4 5 6 6 | (7-6)
7 6 5 4 3 2 1 2 3 4 5 6 7 7 | (7-7)
8 | (n-i)
Enter the number of lines: 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
Using four loops, one to loop through the line, one to print spaces and two other to print numbers, decreamentally and inecrementally.
|line number|number of 2-spaces|
1 1 | (7-1)
2 1 2 2 | (7-2)
3 2 1 2 3 3 | (7-3)
4 3 2 1 2 3 4 4 | (7-4)
5 4 3 2 1 2 3 4 5 5 | (7-5)
6 5 4 3 2 1 2 3 4 5 6 6 | (7-6)
7 6 5 4 3 2 1 2 3 4 5 6 7 7 | (7-7)
8 | (n-i)
import java.util.Scanner; public class ProgrammingEx5_17 { public static void main(String[] args) { System.out.print("Enter the number of lines:"); Scanner input = new Scanner(System.in); //get the total number of lines n. int n = input.nextInt(); //Loop through the lines from 1 to n for (int i = 1; i <= n; i++) { // printing spaces, 2 at a time from j=1 to j= n-i for (int j = 1; j <= (n - i); j++) { System.out.print(" "); } //Printing number decreamentally from the line number j to 1 for (int j = i; j >= 1; j--) { System.out.print(j + " "); } //Printing number increamentally from 2 to line number j for (int j = 2; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } } }
No comments:
Post a Comment