The even-odd alternating number triangle switches between odd and even numbers on every row: 1 on the first row, 2 4 on the second, 1 3 5 on the third. Odd rows list odd numbers and even rows list even numbers.
Quick answer: Row i prints i numbers, and the number at position j is 2j − (i % 2). On odd rows i % 2 is 1, giving 1, 3, 5; on even rows it is 0, giving 2, 4, 6. One formula covers both kinds of row.
This program is part of the Series Patterns collection.
Table of contents8 sections
Even-Odd Alternating Number Triangle output
Output (n = 5):
1 2 4 1 3 5 2 4 6 8 1 3 5 7 9

How the even-odd alternating number triangle works
The j-th even number is 2j and the j-th odd number is 2j − 1. They differ by exactly 1, and i % 2 is exactly 1 on odd rows and 0 on even ones. Subtracting it therefore switches between the two lists without an if. The row length is the usual i, so the shape is a right triangle.
- Run the outer loop for
ifrom1ton, one row per pass. - Print
inumbers (value2 × j − i % 2). - Move to the next line.
Key takeaways
2jis thej-th even number and2j − 1thej-th odd one.- Subtracting
i % 2switches between them without an if. - Odd rows hold odd numbers; even rows hold even numbers.
- Every row restarts at 1 or 2, so the numbers never get large.
Even-Odd Alternating Number Triangle in C
#include <stdio.h>
int main(void) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
printf("%3d", 2 * j - i % 2);
printf("\n");
}
return 0;
}Even-Odd Alternating Number Triangle in C++
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << setw(3) << 2 * j - i % 2;
cout << endl;
}
return 0;
}Even-Odd Alternating Number Triangle in Java
public class EvenOddAlternatingTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
System.out.printf("%3d", 2 * j - i % 2);
System.out.println();
}
}
}Even-Odd Alternating Number Triangle in Python
n = 5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(f"{2 * j - i % 2:3d}", end="")
print()Time and space complexity
The program prints one character for each position in the pattern, so for n rows it runs in O(n²) time. It only needs a few loop variables, so the extra memory is O(1).
Frequently asked questions
How is it different from the odd number triangle?
The odd number triangle uses odd numbers on every row. This one swaps to even numbers on every second row.
How do I start with even numbers on the first row?
Use 2j − ((i + 1) % 2). Row 1 then prints 2 and row 2 prints 1 3.
What does the last column show?
The last number of row i is 2i − (i % 2): 1, 4, 5, 8, 9. It climbs by 3, then 1, then 3, then 1, because the rows switch between odd and even lists.
Can I write it with an if instead?
Yes: print 2j − 1 when i is odd and 2j otherwise. The remainder trick is shorter and gives the same output.








