Square Number Pyramid Pattern in Java

Beginner
⏱️ 5 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Nested Loops

What You’ll Learn

How to print a centered pyramid of squared numbers in Java using nested for loops and formatted output.

Each row prints an odd number of values (1, 3, 5, …), and the printed values are m*m for an incrementing counter m.

⭐ Pattern Output

For rows = 5, the pattern looks like this:

Output
                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625
1

Complete Java Program

This version prints a centered pyramid where each number is the square of an incrementing counter m.

Java
public class Main {
    public static void main(String[] args) {
        int rows = 5;
        int maxOdd = 2 * rows - 1;

        int m = 1;
        for (int i = 1; i <= maxOdd; i += 2) {
            for (int j = i; j < maxOdd; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%4d", m * m);
                m++;
            }
            System.out.println();
        }
    }
}

🧠 How It Works

1

Pick the pyramid height

rows = 5 sets the number of lines. The widest line will have 2*rows-1 values.

Setup
2

Outer loop creates odd widths

i = 1, 3, 5, ... controls how many numbers print on each row. Odd widths keep the pyramid symmetric.

Row control
3

Leading spaces center the row

The loop j = i .. maxOdd-1 prints spaces first. Smaller rows get more spaces, so the pyramid stays centered.

Alignment
4

Print squared numbers with formatting

System.out.format("%4d", m*m) prints each square in a 4-character field so columns align.

Number printing
=

Square number pyramid

Total numbers printed are \(1 + 3 + 5 + \dots + (2n-1) = n^2\), so runtime grows like O(n²).

2

Variation — User Input Version

Let the user choose the pyramid height using Scanner:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();
        int maxOdd = 2 * rows - 1;

        int m = 1;
        for (int i = 1; i <= maxOdd; i += 2) {
            for (int j = i; j < maxOdd; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%4d", m * m);
                m++;
            }
            System.out.println();
        }

        sc.close();
    }
}

💡 Tips for Enhancement

Try These

  • Change squares to cubes with m*m*m
  • Print separators (like a space) between columns if you don’t need fixed-width formatting
  • Restart counting on each row by resetting m (to create repeated rows)
  • Use StringBuilder to build each line if you want more complex spacing rules
  • Try printing only odd squares ((2m-1)^2) for a different sequence

Avoid

  • Printing unformatted numbers (alignment will break as values grow)
  • Using negative/zero rows without validating input
  • Forgetting to move to the next line after each row
  • Closing System.in with Scanner if you need console input later in the same JVM run

Key Takeaways

1

Row widths are odd: 1, 3, 5, … up to 2*rows-1.

2

A counter m generates values and the program prints m*m on each step.

3

Center alignment comes from printing leading spaces before each row.

4

Total printed numbers are , so runtime grows like O(n²).

❓ Frequently Asked Questions

Odd widths (1, 3, 5, ...) make the pyramid symmetric. The last row has 2*rows-1 values.
It prints every number in a 4-character column, keeping alignment consistent even when values grow to 3 digits (like 121) or more.
Replace m * m with m * m * m. Keep the same loop structure and formatting.
O(n²) for n rows because you print \(1+3+5+\dots+(2n-1) = n^2\) numbers.

Explore More Java Number Patterns!

Pyramids are a great way to practice alignment + formatting in nested loops.

All Number Patterns →
Did you know?

The sequence of odd widths has a neat identity: 1 + 3 + 5 + … + (2n-1) = n². That’s why a pyramid with n rows prints exactly numbers.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful