Alternating Row Zigzag Number Pattern in C

What You’ll Learn
How to print an alternating row ascending/descending number pattern in C. Rows switch direction based on whether the current row length is odd or even.
This is an excellent pattern to practice nested loops + if/else logic.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
4321
123
21
1Complete C Program
If the row length i is odd, print 1..i. If it’s even, print i..1.
#include <stdio.h>
int main() {
int rows = 5;
int i, j;
for (i = rows; i >= 1; --i) {
if (i % 2 != 0) {
for (j = 1; j <= i; ++j) {
printf("%d", j);
}
} else {
for (j = i; j >= 1; --j) {
printf("%d", j);
}
}
printf("\n");
}
return 0;
}🧠 How It Works
Outer loop controls row length
i counts down from rows to 1. Each iteration prints one line with exactly i digits.
Odd rows print ascending
When i is odd, run j = 1..i to print 123...i.
Even rows print descending
When i is even, run j = i..1 to print a countdown like 4321.
Zigzag effect
Direction alternates by row parity, producing a zigzag. Total prints remain n(n+1)/2 so time complexity is O(n²).
Variation — User Input Version
Accept the number of rows from the user:
#include <stdio.h>
int main() {
int rows;
int i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
if (i % 2 != 0) {
for (j = 1; j <= i; ++j) {
printf("%d", j);
}
} else {
for (j = i; j >= 1; --j) {
printf("%d", j);
}
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Reverse the alternation (even ascending, odd descending)
- Add spaces for readability:
printf("%d ", j) - Use a different rule (every 3 rows switch direction)
- Print only odd numbers or even numbers for a variation
Avoid
- Duplicating logic with separate variables when one loop variable is enough
- Forgetting the newline after each row
- Not validating user input
Key Takeaways
Odd row lengths print ascending; even row lengths print descending.
i % 2 decides the direction for each row.
Total prints are still n(n+1)/2 so the runtime stays O(n²).
This pattern demonstrates how small conditionals can create big visual changes.
❓ Frequently Asked Questions
i is odd or even using i % 2, and choose a different inner loop direction.i % 2 == 0 and descending when i % 2 != 0.Explore More Zigzag Patterns
Alternating direction is a powerful trick. Try alternating symbols, spaces, or even prime numbers per row.
Zigzag patterns are a common stepping stone to more advanced tasks like snake/spiral matrix printing, because both rely on switching direction based on parity.
12 people found this page helpful
