Alternating Odd/Even Number Triangle in C++

What You’ll Learn
How to print a triangle where odd rows contain odd numbers and even rows contain even numbers:
1, 2 4, 1 3 5, 2 4 6 8, 1 3 5 7 9
We choose a starting value based on the row index (1 or 2), then keep adding 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
For each row i, start k as 1 (odd row) or 2 (even row), then print i values by doing k += 2.
#include <iostream>
using namespace std;
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++) {
cout << k << " ";
k += 2;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the number of rows
int rows = 5; controls how many lines to print.
Outer loop (rows)
for (i = 1; i <= rows; i++) increases the row length from 1 to rows.
Pick odd/even start
k = (i % 2 == 0) ? 2 : 1; sets k to 2 on even rows and 1 on odd rows.
Inner loop (print and add 2)
Printing k and then doing k += 2 keeps the row odd-only or even-only.
Alternating odd/even triangle
Odd rows build 1,3,5,... and even rows build 2,4,6,... using the same k += 2 rule.
Variation — User Input Version
Let the user choose the number of rows at runtime. We keep the same odd/even row logic.
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j, k;
cout << "Enter the number of rows: ";
cin >> rows;
if (!cin || rows <= 0) return 0;
for (i = 1; i <= rows; i++) {
k = (i % 2 == 0) ? 2 : 1;
for (j = 1; j <= i; j++) {
cout << k << " ";
k += 2;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Remove trailing spaces by printing a space only between values
- Start even rows from a different even number (like 0) for another variation
- Right-align the triangle by printing leading spaces before each row
- Replace the numbers with characters (A/C/E for odd rows, B/D/F for even rows)
- Convert this into a function to reuse across multiple patterns
Avoid
- Using
endlinside loops (unnecessary flushing) - Forgetting to reset
kat the start of every row - Mixing the row counter (
i) and position counter (j) logic - Not validating user input before using
rows
Key Takeaways
Odd rows start from 1 and print odd numbers by adding 2.
Even rows start from 2 and print even numbers by adding 2.
Resetting k each row is what makes the pattern alternate correctly.
Printing \(1+2+\dots+n\) values makes the pattern growth quadratic.
❓ Frequently Asked Questions
i. If i is even, it starts at 2; otherwise it starts at 1.j < i).Explore More C++ Number Patterns!
Alternating rules like parity (odd/even) are a fun way to practice nested loops.
Adding 2 repeatedly keeps numbers in the same parity group (all odd or all even). That’s why k += 2 is perfect for this pattern.
12 people found this page helpful
