Alternating Zigzag Number Triangle in C

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
If / Else + Loops

What You’ll Learn

The alternating zigzag number triangle combines nested loops with an if/else parity check to flip print direction each row. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

odd i: 1..i, even i: i..1

Row length 5 prints 12345; length 4 prints 4321; length 3 prints 123, and so on.

Outer Loop

Rows

for (i = rows; i >= 1; i--) walks each line from the longest down to a single digit.

Parity Branch

if / else

if (i % 2 == 0) prints descending; else prints ascending with printf("%d", j).

printf vs newline

Same line / next line

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

Live Preview

1–20 rows

Pick a row count and draw the zigzag number triangle instantly in the browser.

O(n²)

Complexity

Total digit prints still = n(n+1)/2; extra memory stays O(1).

Introduction

An alternating zigzag number triangle shrinks each row while flipping print direction based on row length parity. With rows = 5, the output is 12345, 4321, 123, 21, 1.

In C you solve it with a descending outer loop plus an if/else: odd i uses for (j = 1; j <= i; j++), even i uses for (j = i; j >= 1; j--), then printf("\n") ends each row.

Why it matters?

It introduces conditions inside loops — a stepping stone from pure nested loops to logic-heavy pattern problems.

Key Highlights

Parity Switches Direction

Odd i prints 1..i; even i prints i..1.

If / Else Branch

i % 2 picks ascending vs descending inner loop.

Print Then Break

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

Series Foundation

Follow Program 12; continue to Program 14 (odd-length rows).

In short: for each row length i from rows down to 1, use i % 2 to print 1..i or i..1, then call printf("\n").

📝 Problem & Approach

Given a positive integer rows, print an alternating zigzag number triangle: row length i prints digits ascending when i is odd and descending when i is even, with the outer loop counting from rows down to 1.

c
// First 5 rows (conceptual shape)
// 12345
// 4321
// 123
// 21
// 1

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextEach row prints sequential digits; odd-length rows ascend, even-length rows descend.

Minimal workflow

Pseudocode
for i from rows down to 1:
    if i is even:
        for j from i down to 1: print j
    else:
        for j from 1 to i: print j
    print newline

Approach comparison

ApproachIdeaBest for
if/else + nested loopsParity branch + inner directionLearning and interviews
Direction variablesCompute start, end, step from parityShorter production-style demos

⚡ Quick Reference

GoalPattern
Walk each rowfor (i = rows; i >= 1; i--)
Odd row: ascendingfor (j = 1; j <= i; j++) printf("%d", j);
Even row: descendingfor (j = i; j >= 1; j--) printf("%d", j);
Parity checkif (i % 2 == 0) { ... } else { ... }
End the rowprintf("\n");
Program 12 variantfor (j = i; j <= rows; j++) printf(i) (repeating digits)

📋 Ascending vs Descending vs Parity

Same zigzag triangle — different ways to pick inner-loop direction.

Ascending (odd i)
1..i

Prints 123 when row length is 3

Descending (even i)
i..1

Prints 4321 when row length is 4

i % 2
parity

Even i reverses; odd i goes forward

Learning tip
if/else first

Master explicit branches before direction variables

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditions inside nested loops.

  1. First lab exercise

    Most C pattern series start here before pyramids and diamonds.

  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 12 (11111, 2222, …) and Program 14 (odd-length rows) 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 zigzag number 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, scanf input, and a direction-variables refactor. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating zigzag number triangle with if/else branches.

Example 1 — Fixed rows = 5

Hard-coded height — odd rows ascend, even rows descend.

c
#include <stdio.h>

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

    for (i = rows; i >= 1; --i) {
        if (i % 2 == 0) {
            for (j = i; j >= 1; --j) {
                printf("%d", j);
            }
        } else {
            for (j = 1; j <= i; ++j) {
                printf("%d", j);
            }
        }
        printf("\n");
    }

    return 0;
}

How It Works

When i = 5 (odd), the inner loop prints 12345. When i = 4 (even), it prints 4321, and so on until i = 1 prints 1. printf("\n") after the inner loop starts the next row.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with scanf("%d", &rows) (check the return value in real apps).

c
#include <stdio.h>

int main() {
    int rows;
    int i, j;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for (i = rows; i >= 1; --i) {
        if (i % 2 == 0) {
            for (j = i; j >= 1; --j) {
                printf("%d", j);
            }
        } else {
            for (j = 1; j <= i; ++j) {
                printf("%d", j);
            }
        }
        printf("\n");
    }

    return 0;
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Direction Variables

Same zigzag shape with one inner loop and computed start/end/step.

Example 3 — Direction Variables

Replace the if/else blocks with start, end, and step values derived from parity.

c
#include <stdio.h>

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

    for (i = rows; i >= 1; --i) {
        int start = (i % 2 == 0) ? i : 1;
        int end = (i % 2 == 0) ? 1 : i;
        int step = (i % 2 == 0) ? -1 : 1;

        for (j = start; step > 0 ? j <= end : j >= end; j += step) {
            printf("%d", j);
        }
        printf("\n");
    }

    return 0;
}

How It Works

start, end, and step encode the same ascending/descending logic as the if/else version in one inner loop. Great once you understand parity branching; keep the explicit if/else for exams that ask you to show both inner loops.

🧠 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 (rows)

for (i = rows; i >= 1; i--) picks the row length; parity decides print direction.

Row
3

Parity branch

if (i % 2 == 0) runs descending j; else runs ascending j with printf("%d", j).

Direction
4

New line

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

Break
=

Zigzag complete

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

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop value of i and note whether the row prints ascending or descending.

iParityInner j rangePrinted row
4even4..14321
3odd1..3123
2even2..121
1odd1..11

Total digit 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: swap if/else branches to flip odd/even direction.

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 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 the if/else version first; treat direction variables as a polish refactor afterward.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer scanf

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

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

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

  4. 4. Use i % 2 for Direction

    if (i % 2 == 0) is the standard parity check for zigzag rows.

  5. 5. Dry-Run One Small n

    Trace rows = 3 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 zigzag number patterns.

  1. 1. printf("\n") Inside the Inner Loop

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

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

  2. 2. Swapped Inner Bounds

    Using ascending on even rows or descending on odd rows reverses the zigzag.

    → Even i: j = i; j >= 1; j--. Odd i: j = 1; j <= i; j++.

  3. 3. Forgetting the Row Break

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

    → Always end the row after the inner loop.

  4. 4. Unchecked scanf

    Letters or empty input throw undefined rows.

    → Prefer scanf and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to i = 0 without adjusting the inner bound prints an empty first row or wrong counts.

    → If 0-based, print i with wrong inner bound (e.g. j <= i + 1).

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.

Fill char

Flipped parity rule

Swapping if/else still works — output direction mirrors, not broken.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Shrinking repeating pattern

  • Repeat digit i with for (j = i; j <= rows; j++)
  • Continue with Program 12

2. Odd-length descending triangle

  • Outer loop steps by 2 (7, 5, 3, 1)
  • Continue with Program 14

3. Flip parity rule

  • Swap if/else so odd rows descend
  • Compare output with the default zigzag

4. Spaced digits

  • Use printf("%d ", j) between digits
  • Harder follow-up after this page

Notes

  • Triangular count. Total digit prints for n rows is n(n+1)/2 — hence O(n²) time.
  • printf 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 sets row length, i % 2 picks ascending or descending inner loop, then break the line.

⏱️ Time and Space Complexity

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

🎉 Conclusion

The alternating zigzag number triangle combines nested loops with parity branching — a natural step after repeating-digit patterns. Master the if/else version, then optionally refactor rows with start/end/step direction variables.

Practice the three examples above, then continue to Program 14 for odd-length descending rows.

Odd i prints 1..i; even i prints i..1 — keep printf("%d", j) for digits and printf("\n") for the break.

💡 Best Practices

✅ Do

  • Explain parity rule before coding: odd ascends, even descends
  • Use printf("%d", j) for digits and printf("\n") after 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
  • Swap ascending/descending branches between odd and even rows
  • 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 zigzag pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Controls row length each line

Code
% 03

Parity

i % 2 picks direction

Logic
04

printf("\n")

Ends each row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The program checks whether i is even or odd. For odd i it prints 1..i ascending; for even i it prints i..1 descending, creating a zigzag direction.
The second row from the top has length i = 4, which is even. The even branch runs for (j = i; j >= 1; j--) and prints 4, 3, 2, 1.
printf("%d", j) stays on the same line. printf("\n") ends the current line. Digits use printf; the row break uses printf("\n") after the inner loop.
Remove the if/else and keep only one inner loop — either 1..i for ascending or i..1 for descending on every row.
Program 12 repeats the row digit with for (j = i; j <= rows; j++) (11111, 2222, 333, 44, 5). Program 13 prints sequential digits 1..i or i..1 and alternates direction using i % 2.
O(n²) where n is the number of rows. Total printf digit calls equal n+(n-1)+…+1 = n(n+1)/2.
Yes. Swap the if and else branches so odd rows descend and even rows ascend — the zigzag still works, just mirrored.
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? 🔊

Odd row length i prints 1..i; even row length prints i..1. The outer loop shrinks from rows to 1, and i % 2 flips direction — still O(n²) total digit prints.

Continue to Program 14

Move on to the odd-length descending number triangle in the C number-pattern series.

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