Column-Wise Alternating Binary Triangle in C++

What You’ll Learn
How to print a binary number triangle where digits alternate by position (column):
1, 10, 101, 1010, 10101
The core idea is printing j % 2 while j counts up from 1.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
10
101
1010
10101Complete C++ Program
The outer loop controls the number of rows. For each row i, the inner loop runs from 1 to i and prints j % 2 to form 1010....
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
cout << (j % 2);
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the row count
int rows = 5; sets how many lines the triangle prints.
Outer loop (rows)
for (i = 1; i <= rows; i++) increases row length from 1 to rows.
Inner loop (print 1010...)
for (j = 1; j <= i; j++) prints j % 2, giving 1 for odd positions and 0 for even positions.
New line
cout << "\\n"; moves to the next row.
Column-wise alternating triangle
Total printed digits are 1+2+…+n = n(n+1)/2, so the time complexity is 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 = 1; j <= i; j++) {
cout << (j % 2);
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Invert the digits by printing
1 - (j % 2) - Add spaces:
cout << (j % 2) << ' '; - Right-align the triangle by printing leading spaces before each row
- Increase
rowsfor a bigger pattern - Replace digits with characters to create alternating alphabet patterns
Avoid
- Using
endlinside loops (unnecessary flushing) - Not checking user input before using
rows - Mixing row/column responsibilities between loops
- Forgetting the newline after each row
Key Takeaways
The outer loop grows the triangle from 1 row item up to rows.
j % 2 produces an alternating sequence by position: 1,0,1,0,...
Counting j upward makes row 2 print 10 (instead of 01).
Time complexity is O(n²) because you print about \(n(n+1)/2\) digits.
❓ Frequently Asked Questions
i. For row 2: 1 % 2 = 1 and 2 % 2 = 0, producing 10.j = 1..i), so row 2 becomes 10. In Program 15, counting down makes row 2 become 01.1 - (j % 2) to invert all digits, or start j from 0 and print j % 2.Explore More C++ Number Patterns!
Small variations (like loop direction) can create a completely different-looking pattern.
For alternating patterns, you can often replace a full if condition with a single expression like j % 2.
12 people found this page helpful
