Rotating Number Pattern in C

What You’ll Learn
How to print a rotating number pattern (circular shift) in C. Each row starts from i, prints up to rows, then wraps around to print 1 up to i-1.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
23451
34512
45123
51234Complete C Program
Use two loops per row: first print i..rows, then print 1..i-1 to wrap around.
#include <stdio.h>
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; ++i) {
for (j = i; j <= rows; ++j) {
printf("%d", j);
}
for (j = 1; j < i; ++j) {
printf("%d", j);
}
printf("\n");
}
return 0;
}🧠 How It Works
Pick the row count
int rows = 5; sets the range 1..rows.
Outer loop picks the start
i is the starting number for each row: 1, 2, 3, ...
Print i..rows
for (j = i; j <= rows; ++j) prints the tail of the sequence.
Wrap around: print 1..i-1
for (j = 1; j < i; ++j) prints the remaining prefix to complete the rotation.
Circular shift output
Each row prints exactly rows digits, so the time complexity is O(n²) for n rows.
Variation — User Input Version
Accept the row count at runtime and use the same wrap-around logic:
#include <stdio.h>
int main() {
int rows;
int i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = i; j <= rows; ++j) {
printf("%d", j);
}
for (j = 1; j < i; ++j) {
printf("%d", j);
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces between digits with
printf("%d ", j) - Rotate in the opposite direction by swapping the print order
- Change the range (e.g. 1..9) by increasing
rows - Use characters instead of digits for rotating alphabet patterns
Avoid
- Forgetting the second loop (wrap-around won’t happen)
- Printing
itwice (keep the wrap loop asj < i) - Using invalid row inputs (consider validating
rows > 0)
Key Takeaways
Each row is the sequence 1..rows rotated to start at i.
Two loops per row implement the wrap-around: i..rows then 1..i-1.
Each row prints exactly rows values, so it’s O(n²) for n rows.
This is a great exercise for understanding circular sequences and loop boundaries.
❓ Frequently Asked Questions
i..rows, the second loop prints 1..i-1 to complete the row with a circular shift.printf("%d ", j) in both loops.1..i-1 first, then i..rows.Explore More C Number Patterns!
Keep practicing with more circular, triangular, and pyramid number patterns.
The wrap-around logic here is similar to how modulo arithmetic works for cyclic sequences (like clocks), but implemented with simple loop ranges.
6 people found this page helpful
