Java Practice Program: pyramid alphabetical order

Write a Java program that prints a pyramid pattern of letters in alphabetical order.

This Java program prints a pyramid pattern of letters in alphabetical order. It uses nested loops, where each row of the pyramid contains letters starting from A.

class Main {
    public static void main(String[] args) {
     int row=5;
        for(int i=1;i<=row;i++){
            for(int j=i;j<=row;j++){
                System.out.print(" ");
            }
            for(int k=1;k<=(2*i-1);k++){
                char latter=(char) ('A'+k-1);
                System.out.print(latter+" ");
            }
            System.out.println();
        }
    }
}

Output:

     A 
   A B C 
  A B C D E 
 A B C D E F G 
A B C D E F G H I 

Code Breakdown
int row = 5;

Specifies the number of rows for the pyramid. You can adjust this value to change the size of the pyramid.
Outer Loop (for (int i = 1; i <= row; i++))

Controls the number of rows in the pyramid.
First Inner Loop (for (int j = i; j <= row; j++))

Prints spaces before the letters to align them correctly into a pyramid shape.
As i increases, the number of spaces decreases.
Second Inner Loop (for (int k = 1; k <= (2 * i – 1); k++))

Prints the letters for each row.
For row i, it prints 2*i – 1 letters.
(char) (‘A’ + k – 1): Converts the position k into the corresponding uppercase letter starting from A.
System.out.println();

Moves to the next line after printing one row of the pyramid.

Key Points:
Spaces: The number of spaces decreases with each row to create the pyramid shape.
Letters: Letters are printed starting from A. The number of letters in each row is 2*i – 1.
Casting to char: The program uses (char) (‘A’ + k – 1) to calculate the letter based on its ASCII value.

Leave a Reply