Published: 17 Apr 2025
Reading Time: 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.
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.
Start your Java program and define the main method.
Ask the user's input regarding the ideal number of rows for the pyramid.
Example: int rows = 5; (or take user input using Scanner)
Use an outer loop to go from i = 1 to i <= rows.
Each iteration of this loop represents one row in the pyramid.
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.
Add another inner loop that runs from k = 1 to k <= 2 * i - 1 to print the stars for the current row.
After printing spaces and stars for a row, go to the next line using System.out.println();
Complete the program execution.
Here's a Java program that asks the user to enter the number of rows and then prints a pyramid pattern:
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();
}
}
java.util.Scanner to read user input.2 * i - 1, which creates the pyramid shape.System.out.println() moves the cursor to the next line.Enter the number of rows for the pyramid: 8
*
***
*****
*******
*********
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.
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
}
Within each row, two main components need to be printed:
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(" ");
}
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.
}
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:
A pyramid star pattern displays stars centered in each row, increasing in count as you move down.
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();
}
}
}
This program generates a pyramid shape made of stars (*). It uses loops to:
The result is a star pyramid with 5 rows, aligned in the center.
*
***
*****
*******
*********
This pattern starts with the maximum number of stars in the first row and decreases by one in each subsequent row.
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();
}
}
}
*****
****
***
**
*
A sandglass pattern combines an inverted pyramid atop a regular pyramid, forming a sandglass shape.
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();
}
}
}
This program creates a sandglass pattern with stars (*). It's made up of two triangles:
1. Upper Half – Inverted Pyramid
2. Lower Half – Regular Pyramid
*********
*******
*****
***
*
***
*****
*******
*********
A diamond pattern consists of a pyramid followed by an inverted pyramid, forming a symmetrical diamond shape.
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();
}
}
}
1. Number of Rows
rows = 5 defines the height of the diamond's upper half.2. Upper Half (Pyramid)
i = 1 to i = 5 (for each row).3. Lower Half (Inverted Pyramid)
i = 4 down to i = 1 (one less than the upper half). *
***
*****
*******
*********
*******
*****
***
*
A simple number pattern prints numbers sequentially across rows, starting from 1.
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();
}
}
}
This code prints a number pattern in a triangle shape. Here's how it works:
1. Number of Rows
rows = 5 defines how many rows the pattern will have.2. Outer Loop (Rows)
i = 1 to i = 5, controlling the number of rows.3. Inner Loop (Numbers in Each Row)
4. New Line
System.out.println(); moves to the next line.1
12
123
1234
12345
This program generates a triangle pattern using numbers from the Fibonacci sequence.
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();
}
}
}
1. Initialization
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)
3. Inner Loop (columns)
a = b and b = a + b.4. New Row
System.out.println(); moves to the next line.1
1 1
1 1 2
1 1 2 3
1 1 2 3 5
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.
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();
}
}
}
rows = 5 defines how many rows of Pascal's Triangle will be printed.i = 0 to i = 4, handling each row of the triangle.number = (i - j) / (j + 1) × previous number1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
This pattern creates a diamond shape with numbers increasing to 5 and then decreasing symmetrically.
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--;
}
}
}
1. Upper Half of the Diamond
2. Lower Half of the Diamond
rows - 1 (one less row than the upper half). 1
232
34543
4567654
567898765
4567654
34543
232
1
This pattern displays a right-angled triangle formed by consecutive uppercase letters, starting from 'A' and adding one more character in each subsequent row.
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();
}
}
}
System.out.println();A
A B
A B C
A B C D
A B C D E
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'.
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();
}
}
}
System.out.println() moves to the next line. A
A A
A A
AAAAA
A A
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.
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();
}
}
}
System.out.print("K") prints the vertical line of 'K'.j == Math.abs(rows / 2 - i) determines the position of the diagonal 'K'.System.out.println() moves to the next line.K K
K K
K K
KK
K K
K K
K K
To write efficient and readable pyramid pattern programs, consider the following best practices:
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.
Pyramid patterns typically require nested loops:
Ensure that each loop has a clear purpose and that its conditions accurately reflect the pattern's structure.
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.
Choose descriptive variable names that reflect their role in the pattern (e.g., row, space, star). This practice enhances code readability and maintainability.
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.
Ensure loop conditions are optimized to avoid unnecessary iterations. This optimization enhances performance, especially for larger patterns.
Add comments to explain the purpose of each loop and significant operations. Well-commented code is easier to understand and maintain.
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.
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.
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.
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.
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.
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.
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.
Source: NxtWave - CCBP
Original URL: https://www.ccbp.in/blog/articles/pyramid-pattern-in-java