Alternating Odd/Even Number Triangle in C

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo Operator

What You’ll Learn

The alternating odd/even number triangle switches row parity to print odd or even sequences — a natural step after left-shifted odd patterns. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

i % 2 picks parity

Row 1 prints 1, row 2 prints 2 4, row 3 prints 1 3 5, and so on as width grows.

Outer Loop

1..rows

for (i = 1; i <= rows; i++) makes each new row one number longer than the previous.

Inner Loop + k

k += 2 sequence

for (j = 1; j <= i; j++) prints k, then k += 2 keeps odd or even parity on each row.

printf vs newline

Same line / next line

Numbers use printf("%d ", k); end each row with printf("\n").

Live Preview

1–20 rows

Pick a row count and draw the alternating odd/even triangle instantly in the browser.

O(n²)

Complexity

Total prints = rows(rows+1)/2; extra memory stays O(1).

Introduction

An alternating odd/even number triangle grows each row by one number while switching between odd and even sequences using row parity. With rows = 5, the output is 1, 2 4, 1 3 5, 2 4 6 8, 1 3 5 7 9.

In C you pick start value k with i % 2, print k in the inner loop, update k += 2, then printf("\n") ends each row.

Why it matters?

It combines parity checks with growing row width — a step up from Program 17.

Key Highlights

Row Parity

i % 2 picks odd start 1 or even start 2.

k += 2

Stays odd-only or even-only within each row.

Print Then Break

printf("%d ", k) in the inner loop; printf("\n") after.

Series Foundation

Follow Program 17; continue to Program 19 (fill-with-5 triangle).

In short: for each row i from 1 to rows, set k from i % 2, print k then k += 2 for i numbers, then call printf("\n").

📝 Problem & Approach

Given a positive integer rows, print an alternating odd/even triangle: odd rows print odd numbers starting at 1, even rows print even numbers starting at 2, each row has i numbers with k += 2.

c
// rows = 5 (conceptual shape)
// 1
// 2 4
// 1 3 5
// 2 4 6 8
// 1 3 5 7 9

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextEach row has i spaced numbers — odd or even by row parity.

Minimal workflow

Pseudocode
for i from 1 to rows:
    if i is even: k = 2 else k = 1
    for j from 1 to i:
        print k + space
        k += 2
    print newline

Approach comparison

ApproachIdeaBest for
Parity + k += 21, 2 4, 1 3 5, …Learning and interviews
Ternary startk = (i % 2 == 0) ? 2 : 1;Compact user-input version
Flip paritySwap odd/even row assignmentEven rows odd, odd rows even

⚡ Quick Reference

GoalPattern
Walk each rowfor (i = 1; i <= rows; i++)
Pick start by parityif (i % 2 == 0) k = 2; else k = 1;
Print and stepprintf("%d ", k); k += 2;
End the rowprintf("\n");
Ternary shortcutint k = (i % 2 == 0) ? 2 : 1;
Flip parity rowsint k = (i % 2 == 0) ? 1 : 2;

📋 if/else vs Ternary vs Flip Parity

Same alternating triangle — different ways to set the row start value k.

i % 2
parity

Odd row → k=1, even row → k=2

k += 2
sequence

Keeps odd or even within the row

?: ternary
compact

One-line start pick in Example 2

Learning tip
reset k

Set k fresh each outer-loop iteration

Context

When This Pattern Shows Up

Reach for this pattern when teaching row parity and the k += 2 sequence inside nested loops.

  1. First lab exercise

    Natural follow-up after Program 17 — combines parity with growing row width.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with scanf for a flexible row count.

  4. Gateway to variants

    Compare Program 17 (left-shifted odds) and Program 19 (fill-with-5 triangle) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the alternating odd/even triangle in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C programs — fixed row count, compact ternary user input, and flipped parity variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating odd/even triangle with i % 2 and k += 2.

Example 1 — Fixed rows = 5

Hard-coded height — ideal for first demos and screenshots.

c
#include <stdio.h>

int main() {
    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) {
            printf("%d ", k);
            k += 2;
        }
        printf("\n");
    }

    return 0;
}

How It Works

When i = 1 (odd), k starts at 1 and prints once. When i = 2 (even), k starts at 2 and prints 2 then 4. When i = 3, k runs 1, 3, 5 as 1 3 5, and so on as row width grows. printf("\n") after the inner loop starts the next row.

📈 User Input

Read the row count at runtime with scanf.

Example 2 — User Input with Ternary

Read rows with scanf("%d", &rows); use a compact ternary for k.

c
#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;
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. The ternary (i % 2 == 0) ? 2 : 1 replaces the if/else block. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Flip Parity

Swap the assignment so even rows print odds and odd rows print evens.

Example 3 — Flipped Row Parity

Even rows start at 1 (odds); odd rows start at 2 (evens).

c
#include <stdio.h>

int main() {
    int rows = 5;
    int i, j, k;

    for (i = 1; i <= rows; ++i) {
        if (i % 2 == 0)
            k = 1;
        else
            k = 2;

        for (j = 1; j <= i; ++j) {
            printf("%d ", k);
            k += 2;
        }
        printf("\n");
    }

    return 0;
}

How It Works

Swap the if/else branches so even rows get k = 1 and odd rows get k = 2. The inner loop and k += 2 logic stay the same — only parity assignment changes.

🧠 How the Algorithm Prints Rows

1

Set up

#include <stdio.h> brings in printf / scanf. Set rows (fixed or from input).

Setup
2

Outer loop (row width)

for (i = 1; i <= rows; i++) makes each row print i numbers.

Row
3

Parity + inner loop

Set k from i % 2, then printf("%d ", k) and k += 2 for i iterations.

Sequence
4

New line

printf("\n") ends the row so the next outer iteration starts fresh.

Break
=

Alternating triangle complete

Total prints: rows(rows+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop value of i, the starting k, and the numbers printed on each row.

iParityNumbers printedRow output
1odd11
2even2, 42 4
3odd1, 3, 51 3 5
4even2, 4, 6, 82 4 6 8

Total number prints: 1 + 2 + 3 + 4 = 10 = 4×5/2.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j <= i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: use (i + j) % 2 for row+column parity grids.

3. Console Formatting Drills

Practice printf vs row newline without complex math.

Example: put printf("\n") inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: print j + " " for spaced digits on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with scanf return checks and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn i % 2 for row parity first; compare with flipped assignment in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and reset k at the start of each outer-loop iteration.

  2. 2. Prefer scanf

    Check the return value so bad input does not leave rows uninitialized.

  3. 3. Keep printf("\n") Outside

    Only call printf("\n") after the inner loop finishes the row.

  4. 4. Trace k on Paper

    Write row i, start k, and each k += 2 step before coding.

  5. 5. Dry-Run One Small n

    Trace rows = 5 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put printf("\n") inside the inner loop.

Common Pitfalls

Mistakes that commonly break alternating odd/even number patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use printf("%d ", k) for numbers; printf("\n") only after the inner loop.

  2. 2. Forgetting to Reset k

    Reusing k from the previous row mixes odd and even sequences.

    → Set k from i % 2 at the start of each outer-loop iteration.

  3. 3. Using k++ Instead of k += 2

    k++ mixes odd and even numbers within the same row.

    → After each print, update with k += 2 to keep parity.

  4. 4. Forgetting the Row Break

    Omitting printf("\n") glues every number onto one endless line.

    → Always end the row after the inner loop.

  5. 5. Unchecked scanf

    Letters or empty input leave rows uninitialized.

    → Check scanf return value and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric scanf input

Unchecked scanf leaves rows unset — check the return value.

k++

Wrong step on k

k++ mixes odd and even — use k += 2 within each row.

Stale k

Forgot to reset k

Set k fresh each row from i % 2 — do not carry over from the previous row.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Left-shifted odd triangle

2. Fill-with-5 triangle

  • Ascending sequence then pad with n
  • Continue with Program 19

3. Flip row parity

  • Swap odd/even row assignment
  • Compare output with Example 3

4. No trailing space

  • Print space only between numbers, not after the last
  • Harder follow-up after this page

Notes

  • Triangular sum. Total prints = rows(rows+1)/2 — O(n²) for n rows.
  • printf("%d ", k) stays on the line; printf("\n") advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop grows row width, set k from i % 2, print k then k += 2, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Flip parity (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The alternating odd/even number triangle is a compact lesson in row parity: i % 2 picks the start value, and k += 2 keeps each row odd-only or even-only. Master the if/else version, then try the ternary and flip-parity variants.

Practice the three examples above, then continue to Program 19 for the fill-with-5 number triangle.

Reset k each row from i % 2 — use k += 2 inside the inner loop and validate rows when reading input.

💡 Best Practices

✅ Do

  • Explain i % 2 row parity before coding
  • Use printf("%d ", k) and reset k each row
  • Validate rows ≥ 1 for interactive programs
  • Check scanf return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside the inner digit loop
  • Use k++ instead of k += 2 within a row
  • Forget to reset k at the start of each row
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this alternating pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Start k

1 for odd rows, 2 for even

Code
% 03

k += 2

Stays odd or even

Code
04

Grow width

Row i prints i nums

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

We check i % 2. If i is odd, set k = 1 for odd numbers; if i is even, set k = 2 for even numbers.
Row 2 is even, so k starts at 2. The inner loop prints k then adds 2 twice: 2, then 4.
printf("%d ", k) stays on the same line with a trailing space. printf("\n") ends the current line. Numbers use printf; the row break uses printf("\n") after the inner loop.
Row 3 is odd, so k starts at 1 and increments by 2 three times: 1, 3, 5.
After printing k, update k += 2 so the sequence stays odd or even while increasing.
Yes. Change the odd-row start from 1 to 3 and keep k += 2 to stay in the odd sequence.
Yes. Swap the condition so even rows start at 1 and odd rows start at 2.
O(n²) for n rows. Total printf calls equal n+(n-1)+…+1 = n(n+1)/2.
Check scanf's return value: if (scanf("%d", &rows) != 1) handle bad input. Unchecked scanf leaves rows uninitialized on failure.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Row parity picks the start value: odd rows begin at 1, even rows at 2. Then k += 2 keeps each row odd-only or even-only — still O(n²) total prints for n rows.

Continue to Program 19

Move on to the fill-with-5 number triangle in the C number-pattern series.

Program 19 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful