1. Introduction
This blog post will walk you through how to create a Java program that prints an alphabet pyramid, with the pyramid's height determined by user input. This pattern is a fun way to practice loops and conditional statements in Java, using characters instead of numbers. It's an interesting twist on traditional pyramid patterns and is great for understanding character manipulation in programming.
2. Program Steps
1. Import the Scanner class to read the height of the alphabet pyramid from the user.
2. Prompt the user to enter the height of the pyramid.
3. Use nested loops to generate and print the alphabet pyramid: an outer loop for the rows, and nested loops for spaces and alphabets.
4. Compile and run the program, input the desired height, and observe the alphabet pyramid.
3. Code Program
import java.util.Scanner; // Import Scanner class
public class AlphabetPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object
System.out.print("Enter the height of the alphabet pyramid: "); // Prompt for user input
int height = scanner.nextInt(); // Read the height from user
char currentChar = 'A'; // Initialize the starting character
for(int i = 0; i < height; i++) { // Outer loop for each row
for(int j = height - i; j > 1; j--) { // Loop for leading spaces
System.out.print(" ");
}
for(int k = 0; k <= i; k++) { // Loop to print left side of the pyramid
System.out.print(currentChar + " ");
}
currentChar++; // Move to the next character in the alphabet
System.out.println(); // New line after each row
}
scanner.close(); // Close the scanner
}
}
Output:
Enter the height of the alphabet pyramid: 10 A B B C C C D D D D E E E E E F F F F F F G G G G G G G H H H H H H H H I I I I I I I I I J J J J J J J J J J
Explanation:
1. The program begins by importing the Scanner class and prompting the user to input the height of the alphabet pyramid. This height determines how many rows of characters the pyramid will have.
2. A variable currentChar is initialized with 'A', representing the first character to be printed in the pyramid.
3. An outer loop iterates over each row of the pyramid. Within this loop, two nested loops are used: one to print the leading spaces that align the pyramid to the center and another to print the characters on the left side of the pyramid.
4. The character to be printed is incremented (currentChar++) after each row, advancing through the alphabet with each subsequent row.
5. After printing all characters for a row, a newline character (System.out.println()) is used to move to the next row, continuing the pattern until the entire pyramid is formed.
6. Finally, the Scanner object is closed to prevent resource leaks, following best practices for handling user input in Java programs.
Comments
Post a Comment
Leave Comment