Alternating Odd & Even Number Pattern in C

What You’ll Learn
How to print an alternating odd and even number triangle in C. Odd rows print odd numbers (1 3 5 ...) and even rows print even numbers (2 4 6 ...).
This is a nice pattern to practice nested loops plus a tiny rule using i % 2 to decide whether each row starts at 1 or 2.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 4
1 3 5
2 4 6 8
1 3 5 7 9Complete C Program
We pick the row start (k) based on whether the row number is odd or even, then add 2 each time to keep the parity.
#include <stdio.h>
int main() {
int rows = 5;
int i, j, k;
for (i = 1; i <= rows; ++i) {
k = (i % 2 == 0) ? 2 : 1;
for (j = 1; j <= i; ++j) {
printf("%d ", k);
k += 2;
}
printf("\n");
}
return 0;
}🧠 How It Works
Pick how many rows to print
int rows = 5; controls the triangle height.
Outer loop controls rows
for (i = 1; i <= rows; ++i) prints one line per iteration.
Choose odd or even start
If the row is even, start at 2; otherwise start at 1: k = (i % 2 == 0) ? 2 : 1;
Inner loop prints i numbers
for (j = 1; j <= i; ++j) prints k, then does k += 2 to stay odd/even.
Alternating odd/even triangle
Total prints across all rows is 1+2+…+n = n(n+1)/2, so the time complexity is O(n²) for n rows.
Variation — User Input Version
Make the row count dynamic by reading it from the user using scanf():
#include <stdio.h>
int main() {
int rows;
int i, j, k;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
k = (i % 2 == 0) ? 2 : 1;
for (j = 1; j <= i; ++j) {
printf("%d ", k);
k += 2;
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Accept row count from the user with
scanf() - Reverse the rule to start odd rows with even numbers
- Print without trailing spaces by handling the last column separately
- Right-align the triangle by printing leading spaces
- Swap numbers with characters to create alternating alphabet patterns
Avoid
- Forgetting the newline after each row
- Mixing up row parity (odd/even) logic
- Using
k++(it breaks the odd/even sequence) - Allowing negative row counts without validation
- Hard-coding row count when a user-input version is desired
Key Takeaways
Odd rows start with 1 and print odd numbers: 1, 3, 5…
Even rows start with 2 and print even numbers: 2, 4, 6…
k += 2 preserves parity across the row.
This pattern mixes if-else with nested loops — a common interview combo.
❓ Frequently Asked Questions
1 and even rows start at 2, so the rows alternate between odd and even sequences.k = 1 for even rows and k = 2 for odd rows.Explore More C Number Patterns!
Keep practicing nested loops with patterns that add alignment, parity, and spacing rules.
You can generalize this idea to many patterns: pick a row rule (odd/even, prime/composite, increasing/decreasing) and keep the inner loop responsible only for printing the right count for that row.
12 people found this page helpful
