Alternating 1s and 0s Pattern in C

What You’ll Learn
How to print a shrinking triangle where odd rows print 1 and even rows print 0. We use i % 2 to decide the digit for each row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
11111
0000
111
00
1Complete C Program
The outer loop controls row length, while the inner loop prints the same digit for that row (i % 2).
#include <stdio.h>
int main() {
int rows = 5;
int i, j;
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d", i % 2);
}
printf("\n");
}
return 0;
}🧠 How It Works
Count down the row length
for (i = rows; i >= 1; --i) prints 5 digits, then 4, then 3, and so on.
Decide whether to print 1 or 0
i % 2 is 1 for odd i and 0 for even i.
Print the same digit i times
for (j = 1; j <= i; ++j) repeats the digit for that row.
Alternating binary rows
Total printed digits are 1+2+…+n = n(n+1)/2, so time complexity is O(n²).
Variation — User Input Version
Accept the number of rows from the user. The logic stays the same:
#include <stdio.h>
int main() {
int rows;
int i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d", i % 2);
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Flip the pattern by printing
(i + 1) % 2 - Add spacing with
printf("%d ", i % 2) - Print an ascending version by looping
ifrom 1 torows - Replace digits with characters like
A/Bor*/-
Avoid
- Assuming
i % 2alternates within a row (it alternates by row here) - Using negative/zero rows without validating input
- Forgetting the newline after each row
Key Takeaways
Odd rows print 1; even rows print 0 using i % 2.
Row length decreases from rows to 1.
Complexity is O(n²) for n rows.
You can flip the digits easily with (i + 1) % 2.
❓ Frequently Asked Questions
4 % 2 is 0, so the program prints 0 four times.(i + 1) % 2 instead of i % 2 to swap the digits.i % 2, you can print (i + j) % 2 so the digit changes by column too.n(n+1)/2.Explore More C Number Patterns!
Keep practicing with more binary patterns and loop exercises.
The modulo operator is a common tool for pattern problems: x % 2 toggles between 0 and 1, which is perfect for alternating outputs.
6 people found this page helpful
