Rotating Number Pattern in Java

What You’ll Learn
How to print a rotating number pattern in Java:
12345, then 23451, then 34521, and so on.
Each row is built by printing numbers from i to rows, then appending the values from i-1 down to 1.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
23451
34521
45321
54321Complete Java Program
Use one loop to print i..rows, then another loop to print i-1..1.
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) {
System.out.print(j);
}
for (int k = i; k > 1; k--) {
System.out.print(k - 1);
}
System.out.println();
}
}
}🧠 How It Works
Set the size
rows = 5 defines the largest printed digit.
Outer loop chooses the row start
Row i starts printing at i and shifts left each line.
Print the increasing run (i..rows)
for (j = i; j <= rows; j++) prints the increasing part like 2345.
Append the decreasing run (i-1..1)
for (k = i; k > 1; k--) appends digits like 1 or 21.
Rotating rows
Each row prints exactly rows digits, and the overall runtime grows like O(n²).
Variation — User Input Version
Let the user choose the maximum digit 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 maximum number: ");
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) {
System.out.print(j);
}
for (int k = i; k > 1; k--) {
System.out.print(k - 1);
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Print spaces between digits for readability (use
System.out.print(j + " ")) - Store each row in a
StringBuilderto add separators easily - Change the second loop to append
rows..(i+1)for a different rotation style - Use multi-digit formatting (
%2d/%3d) when rows can be > 9 - Try the same logic with characters (A..E) for an alphabet rotation
Avoid
- Hard-coding 5 instead of using
rows - Mixing loop variables (keep
ifor rows,j/kfor columns) - Forgetting the newline after each row
- Assuming single digits when rows can exceed 9
Key Takeaways
Each row is built from two parts: i..rows then i-1..1.
Every row prints exactly rows digits.
The second loop appends the wrap-around tail (like the ending 1 in 23451).
Overall work grows like O(n²) for n rows.
❓ Frequently Asked Questions
i=5, the increasing part is just 5, and the second loop appends 4 3 2 1 (without spaces), giving 54321.j + " " and (k-1) + " " in the loops, or build an array of values and join(" ").Explore More Java Number Patterns!
Rotation-style patterns are great practice for combining an increasing run and a wrap-around tail.
Many “rotation” patterns can be built by printing a main sequence first, then appending a second sequence that wraps back to the beginning.
12 people found this page helpful
