1. Introduction
This tutorial will guide you through creating a Java program that prints a number pyramid, with the height determined by user input. A number pyramid is a pattern in programming that displays numbers in a structured pyramid shape, increasing with each row. This program combines loops and number manipulation, providing a practical example of how mathematical concepts can be implemented in Java programming.
2. Program Steps
1. Import the Scanner class to read input from the console.
2. Prompt the user to enter the number of rows for the number pyramid.
3. Use nested loops to generate and print the pyramid pattern: the outer loop for rows, the first inner loop for leading spaces, and the second inner loop for printing numbers.
4. Compile and run the program, then input the number of rows to generate the pyramid.
3. Code Program
import java.util.Scanner; // Import Scanner class
public class NumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object
System.out.print("Enter the number of rows: "); // Prompt for user input
int rows = scanner.nextInt(); // Read number of rows from user
int currentNumber = 1; // Initialize current number to be printed
for(int i = 1; i <= rows; i++) { // Loop through each row
System.out.format("%" + (rows - i + 1) * 2 + "s", ""); // Print leading spaces for alignment
for(int j = 1; j <= i; j++) { // Loop to print numbers incrementally
System.out.print(currentNumber + " "); // Print current number
currentNumber++; // Increment number for next print
}
System.out.println(); // Move to the next line after each row
}
scanner.close(); // Close the scanner
}
}
Output:
Enter the number of rows: 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
1. The program begins by importing the Scanner class, allowing it to read user input from the console. The user is then prompted to enter the number of rows for the pyramid.
2. An integer variable currentNumber is initialized to 1, which will be used to print numbers in the pyramid starting from 1 and incrementing with each step.
3. The program uses a for loop to iterate over each row. Inside this loop, a formatted print statement is used to create the appropriate amount of leading spaces to align the pyramid centrally.
4. Another nested loop within the outer loop is responsible for printing the numbers. It increments currentNumber with each iteration, ensuring the numbers increase as the pyramid builds.
5. After completing the number printing for a row, a newline is printed to move to the next row, continuing the pattern until the pyramid is complete.
6. Finally, the Scanner object is closed to avoid resource leaks, following best practices for handling user input in Java.
Comments
Post a Comment
Leave Comment