Alternating Ascending & Descending Number Pattern in C

What You’ll Learn
How to print a zigzag number pattern where odd rows print numbers in ascending order and even rows print numbers in descending order, while keeping the overall sequence continuous.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15Complete C Program
We keep a running start value num. Odd rows print forward; even rows print backward.
#include <stdio.h>
int main() {
int row, col, num = 1;
for (row = 1; row <= 5; row++) {
if (row % 2 == 0) {
for (col = num + row - 1; col >= num; col--) {
printf("%2d ", col);
}
} else {
for (col = num; col < num + row; col++) {
printf("%2d ", col);
}
}
printf("\n");
num += row;
}
return 0;
}🧠 How It Works
Track the start value
num is the first number to print on the current row.
Decide direction using modulo
row % 2 is 0 on even rows, so we print those rows in reverse.
Print row numbers
Odd rows print num .. num+row-1. Even rows print num+row-1 .. num.
Advance to the next row
num += row moves the start forward by how many values we printed.
Zigzag sequence
Direction alternates per row while the numbers keep increasing overall.
Variation — User Input Version
Read the number of rows using scanf().
#include <stdio.h>
int main() {
int row, col, num = 1;
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (row = 1; row <= rows; row++) {
if (row % 2 == 0) {
for (col = num + row - 1; col >= num; col--) {
printf("%2d ", col);
}
} else {
for (col = num; col < num + row; col++) {
printf("%2d ", col);
}
}
printf("\n");
num += row;
}
return 0;
}💡 Tips for Enhancement
Try These
- Increase spacing with
%3dor%4dfor larger numbers - Swap logic to make odd rows descending and even rows ascending
- Start from a different value by changing
num
Avoid
- Resetting
numinside the loop (breaks continuity) - Using
rows <= 0without validation
Key Takeaways
Odd rows print ascending; even rows print descending.
row % 2 decides which direction to print.
num keeps the sequence continuous across rows.
Total prints are 1+2+…+n, so runtime is O(n²).
❓ Frequently Asked Questions
num+row-1 down to num on even rows.num to 100 (and keep the rest the same).n rows.Explore More C Number Patterns!
Practice modulo logic and nested loops with more variations.
The total count of printed numbers after n rows is \(1+2+\dots+n = \frac{n(n+1)}{2}\).
12 people found this page helpful
