Back

Learn How to do Pyramid Pattern in Java

17 Apr 2025
7 min read

The Java programming language has numerous pattern printing programs, but one of the most fascinating and, at the same time, the most common in coding interviews is the pyramid pattern.

The pyramid pattern in Java is an excellent way to grasp the concept of nested loops, which are essential for understanding logic and alignment. These patterns can be used to print stars in a triangular form or to create symmetrical designs with numbers in perfect sequence. Working with pyramid patterns not only enhances your programming skills but also improves your writing and critical thinking abilities. Furthermore, they are beneficial for developing your mathematical and logical reasoning skills.

In this blog, you will learn about different types of Java pyramid pattern programs from basic star pyramids to complex number and character patterns. You’ll also learn how to write each pyramid program in Java using a for loop, how to accept input dynamically using a Scanner, and how to avoid common pitfalls beginners face.

What is a Pyramid Pattern in Java?

custom img

A pattern in Java has a specific path that the program follows to produce a result that is a representation of the characters that we wish to have (stars, numbers, or alphabets) and may look like a triangle, or it may be a slab, if we are using loops as a tool. The pattern gets wider by a consistent amount of space and is generally printed in the middle. It forms a shape that looks like a triangle or a pyramid as it is being printed on the computer's screen.

These patterns are usually a must-have programming exercise for you; they help you test your knowledge of loops, the nesting of loops, space, and print logic. A pyramid pattern is definitely a work of art, and it is extremely beautiful and visually appealing after the code has been flowed in no time.

Algorithm for Pyramid Pattern

Step 1: Begin the Program

Start your Java program and define the main method.

Step 2: Get the Number of Rows

Ask the user's input regarding the ideal number of rows for the pyramid.

Example: int rows = 5; (or take user input using Scanner)

Step 3: Loop Through Each Row

Use an outer loop to go from i = 1 to i <= rows.

Each iteration of this loop represents one row in the pyramid.

Step 4: Print Leading Spaces

Before printing stars, use an inner loop that runs from j = 1 to j <= rows - i to print the required spaces. This helps center-align the pyramid.

Step 5: Print Stars

Add another inner loop that runs from k = 1 to k <= 2 * i - 1 to print the stars for the current row.

Step 6: Move to the Next Line

After printing spaces and stars for a row, go to the next line using System.out.println();

Step 7: End the Program

Program to Create Pyramid Pattern in Java

Here's a Java program that asks the user to enter the number of rows and then prints a pyramid pattern of the following:

import java.util.Scanner;

public class PyramidPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user for the number of rows
        System.out.print("Enter the number of rows for the pyramid: ");
        int rows = scanner.nextInt();

        // Loop through each row
        for (int i = 1; i <= rows; i++) {
            // Print spaces to center the stars
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }

            // Print stars for the current row
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }

            // Move to the next line after printing each row
            System.out.println();
        }

        scanner.close();
    }
}

Explanation

  1. Import Scanner Class: We import java.util.Scanner to read user input.​
  2. Prompt for Input: Ask the user to specify how many rows the pyramid should have.
  3. Outer Loop (i): Iterates from 1 to rows. Each iteration represents a row in the pyramid.​
  4. First Inner Loop (j): Prints spaces before the stars to center-align the pyramid. The number of spaces decreases with each row.​
  5. Second Inner Loop (k): Prints the asterisks. The number of stars in each row follows the pattern 2 * i - 1, which creates the pyramid shape.​
  6. New Line: After printing each row, System.out.println() moves the cursor to the next line.​

Output

Enter the number of rows for the pyramid: 8

    *
   ***
  *****
 *******
*********

Use of Loops and Logic in Building Pyramid Coding in Java

​Creating pyramid patterns in Java is a great way to understand the combination of loops and logic. Most of these patterns involve printing characters (e.g., stars or numbers) in a pyramid-like structure. The algorithm for forming these shapes relies mainly on nested loops, where an outer loop takes control of the rows, and the inner loops manage the spaces and characters within each row.​

1. Outer Loop – Controls the Number of Rows

The number of rows in the pyramid is set using the outer loop. Every time this loop is run, it represents single pyramidal row.

int rows = 5; // Total number of rows
for (int i = 1; i <= rows; i++) {
    // Inner loops will be placed here
}

2. Inner Loops – Manage Spaces and Characters

Within each row, two main components need to be printed:​

  • Leading Spaces: To ensure the pyramid is centered, spaces are printed before the characters.​
  • Pattern Characters: Pattern characters refer to symbols like asterisks (*), numbers, or any other characters used to form a specific design or structure based on the desired output.

a. Printing Leading Spaces

The number of leading spaces is reduced in every next row. In this case, if there are n rows in the total, then the first row will have n-1 spaces, the second will have n-2, and so on.

for (int j = i; j < rows; j++) {
    System.out.print(" ");
}

b. Printing Pattern Characters

Pattern characters are displayed only after adding the required leading spaces. The number of characters increases with each row, typically following an odd sequence (1, 3, 5, ...), which maintains the symmetry of the pyramid.​

for (int k = 1; k <= (2 * i - 1); k++) {
    System.out.print("*"); // Change "*" with any extra characters if required.
}

Types of Java Pyramid Pattern Programs

In Java, creating pyramid pattern programs is a common practice to get hands-on experience with nested loops and understand how control flow structures work. These patterns involve printing characters (such as stars, numbers, or letters) in a pyramid-like format. Several kinds of pyramid patterns are frequently used, including:

1. Programs on Star Patterns in Java

Star Pyramid Patterns

A pyramid star pattern displays stars centered in each row, increasing in count as you move down.​

Java Code for Star Pyramid Pattern
public class PyramidPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        for (int i = 1; i <= rows; i++) {
            // Print spaces
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Explanation

This program generates a pyramid shape made of stars (*). It uses loops to:

  1. Go through each row from 1 to 5.
  2. The stars are aligned in a pyramidal pattern by first printing gaps in each row.
  3. Then, it prints an increasing number of stars to form the pyramid.
  4. The number of stars in each row follows the pattern: 1, 3, 5, 7, 9.
  5. It proceeds to the following line once printing each row.

The result is a star pyramid with 5 rows, aligned in the center.

Output
    *
   ***
  *****
 *******
*********

Downward Triangle Star Pattern

This pattern starts with the maximum number of stars in the first row and decreases by one in each subsequent row.​

Java Code for Downward Triangle Star Pattern
public class DownwardTriangle {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        for (int i = rows; i >= 1; i--) {
            // Print stars
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Explanation
  1. This program creates a star-shaped pyramid using loops. 
  2. Each row begins with spaces to push the stars toward the center.
  3. Then, stars are added in increasing count to shape the pyramid.
  4. The stars grow in odd numbers for each row: 1 in the first, 3 in the second, then 5, 7, and finally 9.
  5. After each row is complete, the program moves to the next line.
  6. By the end, it forms a perfectly centered pyramid with five levels of stars.
Output
*****
****
***
**
*

Sandglass Star Pattern

A sandglass pattern combines an inverted pyramid atop a regular pyramid, forming a sandglass shape.​

Java Code for Sandglass Star Pattern
public class SandglassPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of rows

        // Upper half (inverted pyramid)
        for (int i = rows; i >= 1; i--) {
            // Print spaces
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        // Lower half (regular pyramid)
        for (int i = 2; i <= rows; i++) {
            // Print spaces
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Explanation

This program creates a sandglass pattern with stars (*). It’s made up of two triangles:

1. Upper Half – Inverted Pyramid

  • Starts from the widest row (5 stars) and goes upward, reducing the stars.
  • Before printing stars, it prints spaces to keep the pattern centered.
  • The stars are printed in a decreasing pattern: 9 in the first row, then 7, followed by 5, 3, and finally 1 in the last row.
  • This forms the top half of the sandglass.

2. Lower Half – Regular Pyramid

  • Starts from row 2 (to avoid repeating the middle row) and increases stars as it goes down.
  • Again, spaces are printed first to keep the shape centered.
  • The star count grows in this sequence: starting with 3 stars, then 5, followed by 7, and reaching 9 in the final row.
  • This creates the bottom half of the sandglass.
Output
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

Diamond Star Pattern

A diamond pattern consists of a pyramid followed by an inverted pyramid, forming a symmetrical diamond shape.​

Java Code for Diamond Star Pattern
public class DiamondPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of rows

        // Upper half (pyramid)
        for (int i = 1; i <= rows; i++) {
            // Print spaces
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        // Lower half (inverted pyramid)
        for (int i = rows - 1; i >= 1; i--) {
            // Print spaces
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Explanation

1. Number of Rows

  • The variable rows = 5 defines the height of the diamond's upper half.

2. Upper Half (Pyramid)

  • The first part of the code prints the top half of the diamond, which looks like a pyramid.
  • The outer loop runs from i = 1 to i = 5 (for each row).
  • For each row:
    • Spaces are printed first. The number of spaces decreases as you move down the rows (more spaces at the top, fewer at the bottom).
    • Stars are printed next. The number of stars increases in odd numbers: 1, 3, 5, 7, and 9.

3. Lower Half (Inverted Pyramid)

  • Following the upper section, the program prints the lower half of the diamond pattern, forming a inverted pyramid shape.
  • The outer loop runs from i = 4 down to i = 1 (one less than the upper half).
  • For each row:
    • Spaces are printed first, and the number of spaces increases as you move down.
Output
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

2. Numeric Patterns in Java

Simple Number Pattern

A simple number pattern prints numbers sequentially across rows, starting from 1.​

Java Code for Simple Number Pattern
public class SimpleNumberPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}
Explanation

This code prints a number pattern in a triangle shape. Here's how it works:

1. Number of Rows

  • The variable rows = 5 defines how many rows the pattern will have.

2. Outer Loop (Rows)

  • The outer loop runs from i = 1 to i = 5, controlling the number of rows.

3. Inner Loop (Numbers in Each Row)

  • For each row, the inner loop prints numbers starting from 1 up to the current row number (i).
  • For example, in the first row, it prints 1; in the second row, it prints 1 2; and so on.

4. New Line

  • After printing the numbers in each row, System.out.println(); moves to the next line.
​Output
1
12
123
1234
12345

Fibonacci Series Triangle Program in Java

This program generates a triangle pattern using numbers from the Fibonacci sequence.

Java Code for Fibonacci Series Triangle Program
public class FibonacciTriangle {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        int a = 0, b = 1;
        for (int i = 1; i <= rows; i++) {
            a = 0;
            b = 1;
            for (int j = 1; j <= i; j++) {
                System.out.print(b + " ");
                int sum = a + b;
                a = b;
                b = sum;
            }
            System.out.println();
        }
    }
}
Explanation

1. Initialization

  • When rows = 5, it defines the total number of rows in the triangle.
  • a = 0 and b = 1 are the first two numbers in the Fibonacci sequence.

2. Outer Loop (rows)

  • The outer loop runs for each row from 1 to 5.

3. Inner Loop (columns)

  • For each row, the inner loop prints Fibonacci numbers.
  • In each iteration, the current Fibonacci number (b) is printed.
  • Then, the values of a and b are updated using the Fibonacci rule: a = b and b = a + b.

4. New Row

  • After printing all the Fibonacci numbers in the current row, System.out.println(); moves to the next line.
Output
1
1 1
1 1 2
1 1 2 3
1 1 2 3 5

Pascal’s Triangle Program in Java

Pascal's Triangle is a triangular arrangement of numbers where each entry is the sum of the two numbers located directly above it in the row before.

Java Code for Pascal’s Triangle Program
public class PascalsTriangle {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        for (int i = 0; i < rows; i++) {
            int number = 1;
            for (int j = 0; j <= i; j++) {
                System.out.print(number + " ");
                number = number * (i - j) / (j + 1);
            }
            System.out.println();
        }
    }
}
Explanation
  • The rows = 5 defines how many rows of Pascal’s Triangle will be printed.
  • The loop runs from i = 0 to i = 4, handling each row of the triangle.
  • For each row (i), the inner loop runs to print numbers in that row.
  • It calculates each number in Pascal’s Triangle using the formula:
    number=(i−j)(j+1)×previous number\text{number} = \frac{(i-j)}{(j+1)} \times \text{previous number}number=(j+1)(i−j)​×previous number
  • The first number in every row is always 1, and subsequent numbers are calculated based on the previous number.
  • Each row's numbers are printed with spaces between them, and the program moves to the next line after finishing each row.
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Diamond Numeric Pattern Program in Java (1-5-1)

This pattern creates a diamond shape with numbers increasing to 5 and then decreasing symmetrically.​

Java Code for Diamond Numeric Pattern
public class DiamondNumericPattern {
    public static void main(String[] args) {
        int rows = 5; // Half the height of the diamond
        int num = 1;
        
        // Upper half of the diamond
        for (int i = 1; i <= rows; i++) {
            // Print leading spaces
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            // Print increasing numbers
            for (int j = num; j < num + i; j++) {
                System.out.print(j);
            }
            // Print decreasing numbers
            for (int j = num + i - 2; j >= num; j--) {
                System.out.print(j);
            }
            System.out.println();
            num++;
        }
        
        num = rows - 1;
        
        // Lower half of the diamond
        for (int i = 1; i < rows; i++) {
            // Print leading spaces
            for (int j = 0; j < i; j++) {
                System.out.print(" ");
            }
            // Print increasing numbers
            for (int j = num; j < num + rows - i; j++) {
                System.out.print(j);
            }
            // Print decreasing numbers
            for (int j = num + rows - i - 2; j >= num; j--) {
                System.out.print(j);
            }
            System.out.println();
            num--;
        }
    }
}
Explanation

1. Upper Half of the Diamond

  • The outer loop controls the rows for the top half of the diamond.
  • For each row:
    • Leading spaces are printed to center the numbers.
    • The numbers in each row first increase from a starting number (num).
    • Then, the numbers decrease symmetrically after the peak of the row.
    • After finishing each row, num is incremented for the next row.

2. Lower Half of the Diamond

  • After the upper half, the lower half of the diamond is printed.
  • The outer loop for this half goes from 1 to rows - 1 (one less row than the upper half).
  • For each row:
    • Leading spaces are printed, increasing as the rows go down.
    • The numbers first increase starting from num.
    • Then, the numbers decrease symmetrically after the peak.
    • After finishing each row, num is decremented.
Output
    1
   232
  34543
 4567654
567898765
 4567654
  34543
   232
    1

3. Alphabet/ Character Patterns in Java

Right Alphabetic Triangle

This pattern displays a right-angled triangle formed by consecutive uppercase letters, starting from 'A' and adding one more character in each subsequent row.​

Java Code for Right Alphabetic Triangle
public class RightAlphabeticTriangle {
    public static void main(String[] args) {
        int rows = 5; // Number of rows
        for (int i = 1; i <= rows; i++) {
            char ch = 'A';
            for (int j = 1; j <= i; j++) {
                System.out.print(ch + " ");
                ch++;
            }
            System.out.println();
        }
    }
}
Explanation
  • The triangle consist of 5 rows.
  • The loop controls the number of rows to be printed and iterates from 1 to 5.
  • For each row, the character ch is set to 'A' (the first letter of the alphabet).
  • Runs from 1 to i, printing characters in each row.
  • It prints letters starting from 'A' and increases (ch++) with each column in that row.
  • After each row is printed, it moves to the next line using System.out.println();
Output
A
A B
A B C
A B C D
A B C D E

'A' Shape Character Pattern

This pattern forms the shape of the uppercase letter 'A' using characters. It consists of a pyramid with a horizontal line in the middle to represent the crossbar of 'A'.​

Java Code for 'A' Shape Character Pattern
public class AShapePattern {
    public static void main(String[] args) {
        int rows = 5; // Height of the 'A'
        for (int i = 1; i <= rows; i++) {
            // Print leading spaces
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            // Print characters
            for (int k = 1; k <= (2 * i - 1); k++) {
                if (k == 1 || k == (2 * i - 1) || i == rows / 2 + 1) {
                    System.out.print("A");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}
Explanation
  • The outer loop (i) controls the number of rows.​
  • The first inner loop prints spaces to center the characters.​
  • This second inner loop forms the letter's horizontal line by placing 'A' on the sides and in the central row.
  • After each row, System.out.println() moves to the next line.
Output
    A
   A A
  A   A
  AAAAA
 A     A

'K' Shape Character Pattern

This pattern forms the shape of the uppercase letter 'K' using characters. It is made up of two diagonals that meet in the middle: one ascending and one descending.

Java Code for 'K' Shape Character Pattern
public class KShapePattern {
    public static void main(String[] args) {
        int rows = 7; // Total number of rows
        for (int i = 0; i < rows; i++) {
            System.out.print("K");
            for (int j = 0; j < rows; j++) {
                if (j == Math.abs(rows / 2 - i)) {
                    System.out.print("K");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}
Explanation
  • The outer loop (i) iterates over each row.​
  • The first System.out.print("K") prints the vertical line of 'K'.​
  • The inner loop prints spaces and places 'K' at positions that form the diagonals.​
  • The condition j == Math.abs(rows / 2 - i) determines the position of the diagonal 'K'.​
  • After each row, System.out.println() moves to the next line.
Output
K   K
K  K
K K
KK
K K
K  K
K   K

Best Practices for Writing Java Pyramid Pattern Programs

To write efficient and readable pyramid pattern programs, consider the following best practices:​

1. Understand the Pattern Structure

Before coding, analyze the desired pattern to determine the number of rows, columns, and the relationship between them. Recognize how elements like spaces and characters are organized. This understanding will guide your loop structures and output formatting. ​

2. Utilize Nested Loops Effectively

Pyramid patterns typically require nested loops:​

  • Outer Loop: Controls the number of rows.​
  • Inner Loops: Manage spaces and printing of characters or numbers within each row.​

Ensure that each loop has a clear purpose and that its conditions accurately reflect the pattern's structure.​

3. Manage Spaces for Alignment

Proper alignment is crucial for pyramid patterns. Use inner loops to print leading spaces before the main characters in each row. The number of spaces usually decreases as you progress down the rows, creating the pyramid shape. ​

4. Use Meaningful Variable Names

Choose descriptive variable names that reflect their role in the pattern (e.g., row, space, star). This practice enhances code readability and maintainability.​

5. Incorporate User Input for Flexibility

To make your program adaptable, use the Scanner class to accept user input for parameters like the number of rows. This approach allows users to generate patterns of varying sizes without modifying the code. ​

6. Optimize Loop Conditions

Ensure loop conditions are optimized to avoid unnecessary iterations. This optimization enhances performance, especially for larger patterns.​

7. Comment Your Code

Add comments to explain the purpose of each loop and significant operations. Well-commented code is easier to understand and maintain.​

8. Test with Various Inputs

After implementation, test your program with different inputs to ensure it handles various scenarios correctly and produces the expected patterns.​

By following these best practices, you can write efficient, readable, and flexible Java programs to generate pyramid patterns.

Conclusion

​Developing pyramid pattern programs in Java offers a practical approach to deepen your grasp of loops, control structures, and output formatting. By carefully analyzing pattern structures, effectively employing nested loops, aligning spaces properly, and integrating user input, you can craft a diverse array of pyramid patterns. Being vigilant about common pitfalls, such as incorrect loop conditions and mismanagement of spaces, will further enhance your coding skills. These practices not only facilitate pattern creation but also bolster your overall problem-solving abilities in Java programming.​

Frequently Asked Questions

1. Why are pyramid pattern programs commonly used in Java interviews?

Pyramid pattern programs are often used in interviews because they check how well you understand loops, how to build logic, and how to neatly arrange the output on the screen. They also assess logical thinking and problem-solving skills. ​

2. What is the basic structure of a pyramid pattern program in Java?

A typical pyramid pattern program uses nested loops: the outer loop manages the rows, while the inner loops handle spaces and printing characters (like '*'). The number of spaces and characters varies to create the desired pattern. ​

3. How can I create an inverted pyramid pattern in Java?

To create an inverted pyramid, adjust the loops so that the number of characters decreases with each subsequent row. This often involves starting with the maximum number of characters and reducing the count in each iteration. ​

4. What are the common mistakes to avoid when writing pyramid pattern programs?

Common mistakes include incorrect loop conditions leading to extra or missing rows, miscalculating spaces resulting in misaligned patterns, and improper nesting of loops which can disrupt the pattern structure.​

5. Where can I find practice problems for Java pattern programs?

Websites like Programiz and Java Concept of the Day offer a variety of pattern programs, including pyramids, diamonds, and other shapes, which are excellent for practice.

Read More Articles

Chat with us
Chat with us
Talk to career expert