Alternating Odd/Even Number Triangle in C#

What You’ll Learn
How to print an alternating odd/even triangle in C#. Odd rows print odd numbers (1 3 5 ...) and even rows print even numbers (2 4 6 ...).
The key idea is to pick a starting value (k) based on row parity using i % 2, and then increment by 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
Set k to 1 for odd rows and 2 for even rows, then print k and increment it by 2 across the row.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
int i, j, k;
for (i = 1; i <= rows; i++)
{
if (i % 2 == 0)
k = 2;
else
k = 1;
for (j = 1; j <= i; j++)
{
Console.Write(k + " ");
k += 2;
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Outer loop controls the row
i runs from 1 to rows. Each row prints i numbers.
Pick odd/even start using i%2
If i is even, set k = 2 (even numbers). Otherwise set k = 1 (odd numbers).
Inner loop prints and increments by 2
We print k, then update k += 2 so it stays odd or even while increasing.
Alternating odd/even rows
Odd rows print odd numbers; even rows print even numbers.
Variation — User Input Rows
Let the user decide the row count:
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= rows; i++)
{
int k = (i % 2 == 0) ? 2 : 1;
for (int j = 1; j <= i; j++)
{
Console.Write(k + " ");
k += 2;
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Remove trailing spaces by printing a space only between numbers
- Swap odd/even rows by flipping the condition
- Try starting values like 5 (odd rows) and 6 (even rows) to shift the sequences
Avoid
- Forgetting to reset
kfor each row - Using
k++(that mixes odd and even numbers)
Key Takeaways
Row parity (i % 2) decides whether to print odd or even numbers.
k += 2 keeps the sequence odd-only or even-only.
The inner loop prints exactly i numbers on row i.
Total numbers printed is triangular: \(1+2+\dots+n\).
❓ Frequently Asked Questions
k = 2 and then increment by 2 for each print.1 to 3. Just keep using k += 2 to stay odd.n(n+1)/2.Explore More C# Number Patterns!
Try combining parity logic with different loop directions to discover new patterns.
Checking i % 2 is a simple example of parity. Parity checks are also used in hashing, checksums, and error detection.
12 people found this page helpful
