Mirror Number Pattern in Java

What You’ll Learn
How to print the mirror number pattern in Java:
1, then 212, then 32123, up to 543212345.
Each row prints a decreasing sequence from i down to 2, then an increasing sequence from 1 up to i.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
212
32123
4321234
543212345Complete Java Program
Use two inner loops: one prints i..2 (descending), the other prints 1..i (ascending).
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = i; j > 1; j--) {
System.out.print(j);
}
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}🧠 How It Works
Choose the number of rows
rows = 5 prints 5 lines of the mirror pattern.
Outer loop controls the row number
i goes from 1 to rows, and each row gets longer.
Print the left half (descending)
for (j = i; j > 1; j--) prints i i-1 ... 2.
Print the right half (ascending)
for (j = 1; j <= i; j++) prints 1 2 ... i, creating the mirror effect.
Mirror rows
Each row prints 2i-1 digits, and the total work grows like O(n²).
Variation — User Input Version
Let the user choose the row count using Scanner:
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();
for (int i = 1; i <= rows; i++) {
for (int j = i; j > 1; j--) {
System.out.print(j);
}
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Add spaces between digits (
System.out.print(j + " ")) for readability - Center-align the rows by printing leading spaces before the descending part
- Build each row using
StringBuilderfor more complex formatting - Print the pattern upside-down by reversing the outer loop
- Replace numbers with letters to create an alphabet mirror pattern
Avoid
- Printing down to 1 in the first loop (it duplicates the center 1)
- Hard-coding 5 instead of using a
rowsvariable - Forgetting the newline after each row
- Closing
System.intoo early if you need more input later
Key Takeaways
Each row combines a descending and an ascending loop.
The descending loop stops at 2 so the center 1 appears only once.
Row i prints 2i - 1 digits.
Total work grows like O(n²) for n rows.
❓ Frequently Asked Questions
32123. You can add spaces by printing j + " " in both loops.i, the length is 2i-1. For i=5, that’s 9 digits: 543212345.rows - i leading spaces (or space blocks) before the descending loop to center each row.Explore More Java Number Patterns!
Mirror patterns are great practice for combining multiple loops into a single row.
Rows like 32123 are a simple form of a palindrome. Many palindrome patterns are built by printing a descending part and then an ascending part.
12 people found this page helpful
