Alternating Number Triangle in Python

Beginner
⏱️ 10 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Odd/Even Rows

What You’ll Learn

Program 51 prints an alternating number triangle: odd rows go left-to-right, even rows go right-to-left, with a continuous counter across all rows — a natural step after Program 50’s mixed number triangle. This tutorial covers running counters, odd/even row logic, a live preview, worked Python examples, edge cases, and complexity.

Shape Rule

Alternate direction

Row i prints i numbers — ascending on odd rows, descending on even rows.

Running Counter

next

nxt starts at 1 and increments once per printed value — never reset between rows.

Row End Value

end = next + i - 1

Compute end before each row — the last number that belongs on the current line.

Odd/Even Check

i % 2

Odd rows print nxt; even rows print end -= 1 for the zig-zag effect.

Live Preview

rows = 3..9

Pick row count and draw the alternating number triangle in the browser.

O(n²)

Complexity

Total prints = 1+2+…+n = n(n+1)/2 — classic triangular growth.

Introduction

An alternating number triangle pattern prints row i with i continuous numbers — ascending on odd rows, descending on even rows. With rows = 5, you get 1, 3 2, 4 5 6, 10 9 8 7, 11 12 13 14 15.

In Python, a running counter nxt tracks the next value, end = nxt + i - 1 sets the reverse start, and i % 2 picks print direction before print().

Why it matters?

It bridges Program 50’s mixed number triangle to zig-zag patterns — combining a running counter with odd/even row direction.

Key Highlights

Odd rows

Print nxt ascending left-to-right.

Even rows

Print end -= 1 descending right-to-left.

vs Program 50

Program 50 uses fixed digit halves; Program 51 uses a continuous counter with alternating direction.

Series Foundation

Follow Program 50; continue to Program 52 next.

In short: track nxt = 1, compute end = nxt + i - 1, print ascending on odd rows and end -= 1 on even rows, increment nxt each time, then print().

📝 Problem & Approach

Given row count rows = 5, print an alternating number triangle — row i shows i continuous numbers, alternating direction each row.

Python
# rows = 5
//1
//3 2
//4 5 6
//10 9 8 7
//11 12 13 14 15

Inputs & Outputs

ItemTypeDescription
rowsintHow many triangle rows to print.
i (outer)intCurrent row index — runs from 1 to rows.
nxtintRunning counter — next number to assign; increments each print.
endintLast number on the row: next + i - 1; decremented on even rows.
j (inner)intPrint loop — runs 1..i values per row.
Row lengthintRow i prints exactly i numbers.

Minimal workflow

Pseudocode
nxt = 1
for i from 1 to rows:
    end = nxt + i - 1
    for j from 1 to i:
        if i is odd: print nxt
        else: print end; end -= 1
        nxt += 1
    print newline

Approach comparison

ApproachIdeaBest for
Odd/even directioni % 2 picks ascending vs descending printLearning and interviews
Running counternxt increments once per printed valueContinuous numbering across rows
User-input rowsint(input())Flexible row count
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Spaced variantprint(n, end=" ")Easier reading per row

⚡ Quick Reference

GoalPattern
Outer loopfor i in range(1, rows + 1):
Init counternxt = 1
Row end valueend = nxt + i - 1
Odd row printif i % 2 == 1: print(nxt, end=" ")
Even row printelse: print(end, end=" "); end -= 1
Advance counternxt += 1 once per printed value
Program 50 contrastProgram 50 uses fixed digit halves; Program 51 alternates direction with a running counter

📋 Fixed Rows vs User Input vs Compact Trace

Same triangle — three ways to set row count and format output.

Fixed rows
rows = 5

Hard-coded height for demos

User input
int(input())

Read row count from console

Compact trace
rows = 3

Quick dry-run on paper

Running counter
nxt = 1

Continuous numbering across rows

Odd/even
i % 2

Picks ascending vs descending

Context

When This Pattern Shows Up

Reach for this pattern when teaching running counters, odd/even row logic, and zig-zag print direction.

  1. Post Program 50 exercise

    Natural follow-up after Program 50’s mixed number triangle — introduces alternating print direction.

  2. Zig-zag traversal

    Similar logic appears in matrix serpentine traversals and boustrophedon ordering.

  3. Continuous counters

    Total prints = n(n+1)/2 — classic nested-loop complexity example.

  4. Gateway to variants

    Compare Program 50 (mixed number triangle) with this alternating pattern, then continue to Program 52.

  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 running counters, odd/even logic, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the alternating number triangle in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed rows, user input, and a compact trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating number triangle with a running counter and odd/even direction.

Example 1 — Fixed rows = 5

Hard-coded row count — odd rows print nxt ascending, even rows print end descending.

Python
rows = 5
nxt = 1

for i in range(1, rows + 1):
    end = nxt + i - 1

    for _ in range(i):
        if i % 2 == 1:
            print(nxt, end=" ")
        else:
            print(end, end=" ")
            end -= 1

        nxt += 1
    print()

How It Works

When i = 2, the row is even: end = 3, so it prints 3 2 in reverse. When i = 1, the odd row prints nxt = 1 ascending.

📈 User Input

Read row count with int(input()) and validation.

Example 2 — User Input Rows

Read rows with int(input()) and validate the result.

Python
try:
    rows = int(input("Enter the number of rows: "))
except ValueError:
    print("Please enter a positive integer.")
else:
    if rows <= 0:
        print("Please enter a positive integer.")
    else:
        nxt = 1
        for i in range(1, rows + 1):
            end = nxt + i - 1

            for _ in range(i):
                if i % 2 == 1:
                    print(nxt, end=" ")
                else:
                    print(end, end=" ")
                    end -= 1

                nxt += 1
            print()

How It Works

Same counter and odd/even core as Example 1; only the source of rows changes from a literal to user input.

⚡ Compact Trace

Smaller row count for quick tracing on paper or in interviews.

Example 3 — Compact rows = 3

Use rows = 3 to trace the counter and odd/even logic quickly before scaling to 5 rows.

Python
rows = 3
nxt = 1

for i in range(1, rows + 1):
    end = nxt + i - 1

    for _ in range(i):
        if i % 2 == 1:
            print(nxt, end=" ")
        else:
            print(end, end=" ")
            end -= 1

        nxt += 1
    print()

How It Works

With only three rows you can trace every nxt increment and odd/even branch on paper before running the full rows = 5 demo.

🧠 How the Algorithm Prints Rows

1

Init running counter

Set nxt = 1 before the outer loop — it tracks the next number to assign.

Counter
2

Compute row end

end = next + i - 1 — the last number that belongs on row i.

Row math
3

Alternate print direction

Odd rows print nxt; even rows print end -= 1. Increment nxt each time.

Odd/Even
4

New line per row

print() after the inner loop finishes each row.

Break
=

Alternating number triangle complete

Total prints = 1+2+…+nO(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each row’s counter values, print direction, and full line output.

inxt at startendDirectionRow output
111odd / asc1
223even / desc3 2
346odd / asc4 5 6
4710even / desc10 9 8 7
51115odd / asc11 12 13 14 15

Row i always prints exactly i numbers — the counter never resets between rows.

Use Cases

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

1. Teaching Nested Loops

Inner bound grows with outer index — classic nested-loop exercise.

Example: trace row i = 4 in the walkthrough table.

2. Zig-Zag Traversal

Alternating direction mirrors serpentine matrix walks — a common interview pattern.

Example: row 5 ends with 11 12 13 14 15 — five ascending values on an odd row.

3. Output Formatting Drills

Practice print(nxt, end=" ") vs print() with odd/even row direction.

Example: put print() inside the inner loop by mistake.

4. Continuous Counters

Total prints = n(n+1)/2 — links loops to summation formulas.

Example: 10 rows print 55 values total.

5. Complexity Intuition

Growing inner bound makes O(n²) concrete — count prints for n rows.

Example: 5 rows = 1+2+3+4+5 = 15 prints.

6. Input Validation Labs

Pair the pattern with int(input()) and positive-row checks.

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

Pro Tip: when an interviewer asks for patterns, explain 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 inner bounds show up immediately as a broken triangle.

  2. 2. Real Math Connection

    Alternating direction with a running counter — bridges loops to zig-zag logic.

  3. 3. Easy to Extend

    Change rows, use fixed-width format, or switch to full rectangular table.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 2 on paper — watch end = 3 print 3 2 while nxt advances to 4.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Inner bound = i

    Row i prints exactly i values — use for _ in range(i):.

  2. 2. Prefer try/except

    Avoid crashes when the user types letters instead of a number.

  3. 3. print() After Inner Loop

    Only call print() after the inner loop finishes the row.

  4. 4. Fixed-Width Formatting

    Trace rows = 3 on paper before coding the full rows = 5 demo.

  5. 5. Dry-Run rows = 5

    Trace five rows on paper before coding the full 10-row demo.

Pro Tip: if the output is a vertical list of single numbers, you almost certainly put print() inside the inner loop.

Common Pitfalls

Mistakes that commonly break alternating number triangle patterns.

  1. 1. print() Inside Inner Loop

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

    → Use print(nxt, end=" ") or print(end, end=" "); print() only after the inner loop.

  2. 2. Wrong Inner Bound

    Using range(rows) every row makes a full rectangle, not a triangle.

    → Use for _ in range(i): — inner bound depends on outer i.

  3. 3. Resetting the Counter Each Row

    Numbers restart at 1 every line — the continuous sequence breaks.

    → Keep nxt outside the outer loop and only increment it inside the inner loop.

  4. 4. Forgetting print() After Row

    All numbers print on one long line without row breaks.

    → Add print() after each inner loop completes.

  5. 5. Blind int(input())

    Letters or empty input raise ValueError when int(input()) is unchecked.

    → Wrap in try/except ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 on one line.

rows = 0

Empty output

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

Negative

rows < 0

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

rows = 5

Compact trace

Five rows ending with 11 12 13 14 15 — good for dry-runs.

Bad input

Non-numeric input

Unchecked int(input()) raises ValueError — use try/except.

Large rows

Wide output

Row 9 has 9 numbers — total prints grow as n(n+1)/2.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 50

  • Program 50 uses fixed digit halves per row
  • Program 51 uses a continuous counter with alternating direction

2. Change rows

  • Try rows = 4 or rows = 8 in the live preview
  • Same counter logic, different triangle size

3. Next in series

  • Continue with Program 52
  • Build on alternating number patterns

4. Flip parity rule

  • Make odd rows print descending instead
  • Same loops, reversed direction check

Notes

  • Running counter. Init nxt = 1. Compute end = nxt + i - 1 per row. Never reset nxt between rows.
  • print(..., end=" ") stays on the line; print() advances — call it only after the inner loop finishes.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1.
  • Total prints = 1+2+…+n = n(n+1)/2 for n rows — triangular growth, not a full square.

Quick Takeaway: init nxt = 1, compute end = nxt + i - 1, print ascending on odd rows and end -= 1 on even rows, increment nxt each time, then print().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Total prints for n rowsn(n+1)/2 valuesi numbers on row i
Wrap Up

🎉 Conclusion

The alternating number triangle is a natural follow-up to Program 50: a running counter with odd/even row direction for zig-zag output. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 52 for the next pattern in the series.

Row i prints i continuous numbers — ascending on odd rows, descending on even rows.

💡 Best Practices

✅ Do

  • Init nxt = 1 before the outer loop
  • Compute end = nxt + i - 1 at the start of each row
  • Odd rows: print(nxt, end=" ")
  • Even rows: print(end, end=" "); end -= 1
  • Increment nxt += 1 once per printed value

❌ Don’t

  • Reset nxt to 1 on every row
  • Forget to compute end before even rows
  • Call print() inside the inner loop
  • Ignore bad input in user-facing demos
  • Skip the rows = 3 dry-run before coding rows = 5

Key Takeaways

Knowledge Unlocked

Five things to remember about this alternating number triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Counter

nxt = 1, never reset

Code
03

Row end

end = next + i - 1

Code
04

Odd/even

i % 2 picks direction

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Row 2 is an even row, so it prints in reverse order. The row contains numbers 2 and 3, but they are printed as 3 2 using end -= 1.
Even rows print right-to-left to create the alternating effect. We compute end = nxt + i - 1 and decrement while printing.
We use a running counter nxt that increments once per printed value. It is not reset between rows, so numbering continues across the whole triangle.
Before printing row i, the last number is nxt + i - 1. That gives the correct starting point when printing the row in reverse.
Change rows or read it from user input with int(input()) — see Example 2.
O(n²) for n rows because the total printed numbers are 1+2+...+n = n(n+1)/2.
Program 50 concatenates fixed digit sequences per row. Program 51 uses a continuous counter and alternates print direction on odd/even rows.
Yes. Build each row as a list and join with spaces, or print the last value without a trailing space.
Use try/except ValueError around int(input()). Bare int(input()) raises ValueError on bad input.
One row prints 1 — a single ascending value on the first odd row.

Did you Know? 🔊

Numbers stay continuous across rows via a running counter nxt. Odd rows print ascending; even rows print descending using end = nxt + i - 1. Row 2 shows 3 2 — still O(n²) total prints for n rows.

Continue to Program 52

Move on to the next pattern in the Python number-pattern series.

Program 52 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