Java Program to Print Character Pyramid Pattern

1. Introduction

In this blog post, we will delve into creating a Character Pyramid Java Program. This program is a fantastic exercise for beginners to get acquainted with loops and string manipulation in Java. A character pyramid is a structure where characters are arranged in a pyramid shape, increasing or decreasing in number from top to bottom. This simple program will help us understand the basics of Java programming, including loops, data types, and control structures.

2. Program Steps

1. Initialize the program with the necessary variables.

2. Use a for loop to handle the number of rows in the pyramid.

3. Within the loop, use nested loops to print spaces and then characters to form the pyramid shape.

4. Execute the program to display the character pyramid.

3. Code Program

public class CharacterPyramid {
    public static void main(String[] args) {
        int rows = 5; // Number of rows for the pyramid
        char character = 'A'; // Starting character for the pyramid

        for(int i = 1; i <= rows; i++) { // Outer loop for the number of rows
            for(int j = rows; j > i; j--) { // Inner loop for leading spaces
                System.out.print(" "); // Print space
            }
            for(int k = 1; k <= (2 * i - 1); k++) { // Loop for printing characters
                System.out.print(character); // Print the character
                if(k < i) {
                    character++; // Increment character until the middle is reached
                } else {
                    character--; // Decrement character after the middle is reached
                }
            }
            character = 'A'; // Reset character for the next row
            System.out.println(); // Move to the next line
        }
    }
}

Output:

    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA

Explanation:

1. The program starts by defining the number of rows (rows = 5) and the starting character (character = 'A').

2. The outer for loop (for(int i = 1; i <= rows; i++)) iterates over each row.

3. The first inner loop (for(int j = rows; j > i; j--)) prints the leading spaces required to make the pyramid shape.

4. The second inner loop (for(int k = 1; k <= (2 * i - 1); k++)) handles the printing of characters. It increases (character++) the character until the middle of the row is reached, then decreases (character--) it.

5. After completing each row, the character is reset to 'A', and a new line is started with System.out.println().

6. This process repeats until all rows are printed, forming a pyramid shape with characters.

Comments