Alternating Number Pattern in C++

What You’ll Learn
How to print an alternating ascending-descending number pattern in C++: 12345, 4321, 123, 21, 1.
The trick is to use a simple even/odd check on the row size i to decide the direction of printing.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
4321
123
21
1Complete C++ Program
The outer loop shrinks the row length. If i is odd, print 1..i. If i is even, print i..1.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = rows; i >= 1; i--) {
if (i % 2 == 0) {
for (j = i; j >= 1; j--) {
cout << j;
}
} else {
for (j = 1; j <= i; j++) {
cout << j;
}
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the row count
int rows = 5; sets the starting row length.
Outer loop (shrink rows)
for (i = rows; i >= 1; i--) reduces the row length from 5 down to 1.
Decide the direction (odd vs even)
if (i % 2 == 0) chooses descending output for even rows and ascending output for odd rows.
Print the row
If odd, print 1..i. If even, print i..1. Then print a newline with cout << "\\n";.
Alternating direction pattern
Total printed numbers are still triangular: n(n+1)/2, giving O(n²) time complexity for n rows.
Variation — User Input Version
Make the pattern dynamic by reading rows from the user:
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = rows; i >= 1; i--) {
if (i % 2 == 0) {
for (j = i; j >= 1; j--) {
cout << j;
}
} else {
for (j = 1; j <= i; j++) {
cout << j;
}
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces after each number for clarity:
cout << j << ' '; - Swap the parity rule (even ascending, odd descending) to create a new variation
- Start the outer loop from 1..rows to make the triangle grow instead of shrink
- Replace numbers with letters to create alternating alphabet patterns
- Use a boolean toggle (flip each row) instead of parity if you want a different alternation rule
Avoid
- Forgetting to print a newline after each row
- Hard-coding
5everywhere instead of usingrows - Mixing up the loop bounds (descending loop must stop at 1)
- Using
endlinside loops (unnecessary flushing)
Key Takeaways
The outer loop controls the row size by counting down from rows to 1.
A simple parity check (i % 2) decides whether to print ascending or descending.
Odd rows print 1..i; even rows print i..1.
Total work is still triangular: n(n+1)/2 prints in total.
❓ Frequently Asked Questions
i % 2 to choose ascending or descending printing. That makes one row go forward and the next row go backward.cout << j << ' ';. You can also trim the trailing space if needed.Explore More C++ Number Patterns!
Alternate, repeat, align, and experiment—each pattern strengthens your loop thinking.
Parity checks like i % 2 are a simple way to create alternating behavior in patterns without extra counters.
12 people found this page helpful
