Alternating Binary Number Triangle in C++

What You’ll Learn
How to print an alternating binary number triangle in C++:
1, 01, 101, 0101, 10101
The trick is to print 0 and 1 using the modulo operator: j % 2.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
01
101
0101
10101Complete C++ Program
The outer loop controls the number of rows. For each row i, the inner loop counts down from i to 1 and prints j % 2 (odd → 1, even → 0).
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = i; j >= 1; j--) {
cout << (j % 2);
}
cout << "\n";
}
return 0;
}🧠 How It Works
Pick the number of rows
int rows = 5; decides how many lines the triangle prints.
Outer loop (rows)
for (i = 1; i <= rows; i++) grows the row length from 1 to rows.
Inner loop (alternate 1/0)
for (j = i; j >= 1; j--) prints j % 2 for each position, producing alternating 1 and 0.
New line
cout << "\\n"; finishes the current row.
Alternating binary triangle
Total printed digits are 1+2+…+n = n(n+1)/2, so the work grows like O(n²).
Variation — User Input Version
Let the user choose the number of rows at runtime. If the input is invalid or non-positive, we stop early.
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the number of rows: ";
cin >> rows;
if (!cin || rows <= 0) return 0;
for (i = 1; i <= rows; i++) {
for (j = i; j >= 1; j--) {
cout << (j % 2);
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Start with 0 by printing
1 - (j % 2)instead - Add spaces for readability:
cout << (j % 2) << ' '; - Right-align the triangle by printing leading spaces before each row
- Increase
rowsfor a bigger triangle - Use the same idea to build alternating character patterns
Avoid
- Using
endlinside loops (unnecessary flushing) - Not validating user input (can lead to no output or unexpected behavior)
- Mixing loop roles (outer controls rows; inner prints digits)
- Hard-coding values if you want a reusable pattern function
Key Takeaways
The outer loop decides the row length from 1 to rows.
The inner loop prints digits using j % 2, which alternates between 1 and 0.
This pattern is a clean example of combining nested loops with a simple math rule.
Time complexity is O(n²) because you print about \(n(n+1)/2\) digits.
❓ Frequently Asked Questions
j % 2 returns 1 for odd j and 0 for even j. Printing that value creates the alternating effect.2 % 2 = 0), which produces 01. Counting up would produce 10 instead.1 - (j % 2). That swaps 0 and 1 everywhere.Explore More C++ Number Patterns!
Alternating, mirrored, and triangular patterns are a great way to master loops and conditions.
The modulo operator (%) is a common trick in pattern problems: n % 2 immediately tells you whether n is odd (1) or even (0).
12 people found this page helpful
