Alternating 1 and 0 Descending Pattern in C++

What You’ll Learn
How to print a descending triangle where each row contains only one digit that alternates by row:
- Odd rows print 1
- Even rows print 0
You’ll use nested loops for the decreasing length and i % 2 to choose between 1 and 0.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
11111
0000
111
00
1Complete C++ Program
The inner loop prints rows - i + 1 digits. The digit depends on whether the row number i is odd or even.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = i; j <= rows; j++) {
if (i % 2 == 0)
cout << "0";
else
cout << "1";
}
cout << "\n";
}
return 0;
}🧠 How It Works
Decide the size
rows = 5 sets the first row length and the total number of rows.
Outer loop chooses the row number
for (i = 1; i <= rows; i++) moves row by row from 1 to rows.
Inner loop creates decreasing length
for (j = i; j <= rows; j++) runs fewer times each row, so the length becomes rows-i+1.
Pick 1 or 0 using parity
If i % 2 == 0 (even row), print 0; otherwise print 1.
Alternating rows
Total prints follow a triangular number: n(n+1)/2, so the time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user choose the number of rows using cin:
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++) {
for (j = i; j <= rows; j++) {
cout << ((i % 2 == 0) ? "0" : "1");
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Print spaces between digits for readability (e.g.,
cout << digit << ' ') - Swap the alternation (start with 0 on the first row)
- Make it left-aligned or right-aligned by adding leading spaces
- Change digits to characters (e.g., X and O) for a different look
- Validate user input (positive rows) before printing
Avoid
- Forgetting the newline after each row
- Hard-coding
5when you already have arowsvariable - Using
endlin tight loops (it flushes output) - Allowing
rowsto be 0 or negative without checks
Key Takeaways
The outer loop chooses the row index (i).
The inner loop controls the decreasing length (rows-i+1 prints).
i % 2 cleanly alternates between printing 1 and 0.
Total prints are n(n+1)/2, so runtime is O(n²).
❓ Frequently Asked Questions
i is even or odd. Even rows print 0, odd rows print 1.j = i to rows, so row 1 prints 5 digits, row 2 prints 4, and so on.0 when i is odd and 1 when i is even.n(n+1)/2.Explore More C++ Number Patterns!
Once you can control loop bounds and parity, you can build many alternating and zig-zag patterns.
This is the same triangle-length logic as printing 12345, 1234, ... but with the digit fixed per row. Swapping digits (like 2/9) is just changing what you print inside the inner loop.
12 people found this page helpful
