Palindrome Number Triangle in C

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

What You’ll Learn

The palindrome number triangle prints 1, 121, 12321, 1234321, 123454321 — a natural step after the diagonal asterisk pattern in Program 26. This tutorial covers ascending and descending inner loops, mirroring, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

Palindrome rows

Each row reads the same forwards and backwards — 12321 is a palindrome.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) grows the palindrome length each row.

Ascending Loop (j)

1..i

for (j = 1; j <= i; j++) prints the left half of each row.

Descending Loop (k)

i-1..1

for (k = i - 1; k >= 1; k--) mirrors without repeating the peak.

Live Preview

3–9 rows

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

O(n²)

Complexity

Total prints grow as — row i prints 2i - 1 digits.

Introduction

A palindrome number triangle prints an ascending sequence then mirrors it back down on the same row. With rows = 5, the output is 1, 121, 12321, 1234321, 123454321.

In C you use an outer loop for rows, an ascending inner loop j = 1..i, then a descending inner loop k = i-1..1.

Why it matters?

It combines two inner loops for symmetry — a step up from Program 26’s single conditional swap.

Key Highlights

Left 1..i

First inner loop prints ascending digits.

Right i-1..1

Second loop mirrors without repeating the peak.

Palindrome

Each row reads the same forwards and backwards.

Series Foundation

Follow Program 26; continue to Program 28 (0-centered mirror) next.

In short: for each i, print 1..i then i-1..1, then printf("\n").

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print a palindrome triangle: for each i, print 1..i then i-1..1 on the same line.

c
// rows = 5 (conceptual shape)
// 1
// 121
// 12321
// 1234321
// 123454321

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows — outer loop runs from 1 to rows.
iintOuter loop — current row; also the peak digit of the palindrome.
jintAscending loop — prints 1..i (left half).
kintDescending loop — prints i-1..1 (right half).

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from 1 to i:
        print j
    for k from i - 1 down to 1:
        print k
    print newline

Approach comparison

ApproachIdeaBest for
Two inner loops1, 121, 12321, …Learning and interviews
User-input rowsscanf("%d", &rows);Flexible console programs
Spaced outputprintf("%d ", j)Easier reading for wide rows

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Ascending halffor (j = 1; j <= i; j++) printf("%d", j);
Descending halffor (k = i - 1; k >= 1; k--) printf("%d", k);
End the rowprintf("\n");
Spaced digitsprintf("%d ", j); in both loops
User inputscanf("%d", &rows);

📋 Fixed rows vs User Input vs Spaced Output

Same palindrome triangle — different ways to control rows and formatting.

Outer loop
i = 1..rows

Grows palindrome length each row

Left half
j = 1..i

Ascending digits

Right half
k = i-1..1

Mirror without repeating peak

Learning tip
k = i-1

Start mirror at i-1, not i

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetry with two inner loops and palindrome row construction.

  1. Post diagonal exercise

    Natural follow-up after Program 26 — introduces two inner loops for mirroring.

  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 26 (diagonal asterisk) and Program 28 (0-centered mirror) 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 3 and 9 and draw the palindrome 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 C programs — fixed rows, user input, and spaced output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the palindrome triangle with ascending and descending inner loops.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

c
#include <stdio.h>

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

    for (i = 1; i <= 5; ++i) {
        for (j = 1; j <= i; ++j)
            printf("%d", j);

        for (k = i - 1; k >= 1; --k)
            printf("%d", k);

        printf("\n");
    }

    return 0;
}

How It Works

When i = 1, only the ascending loop runs — output 1. When i = 3, print 123 then mirror 21 — output 12321. The second loop starts at i - 1 so the peak digit is not repeated.

📈 User Input

Read the row count with scanf instead of hard-coding 5.

Example 2 — User Input

Read rows with scanf("%d", &rows); both inner loops use i as the bound.

c
#include <stdio.h>

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

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

    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= i; ++j)
            printf("%d", j);

        for (k = i - 1; k >= 1; --k)
            printf("%d", k);

        printf("\n");
    }

    return 0;
}

How It Works

Same two-loop core as Example 1; only the outer bound changes from 5 to rows. The palindrome length grows with each row. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Spaced Output

Add a space between digits for easier reading on wide rows.

Example 3 — Spaced Digits

Keep rows = 5 but print each digit followed by a space in both loops.

c
#include <stdio.h>

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

    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= i; ++j)
            printf("%d ", j);

        for (k = i - 1; k >= 1; --k)
            printf("%d ", k);

        printf("\n");
    }

    return 0;
}

How It Works

Only the print statements change — printf("%d ", j) and printf("%d ", k). Loop bounds and the k = i - 1 start stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

#include <stdio.h> brings in printf / scanf. Set loop variables i, j, k and rows = 5.

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — one palindrome row per iteration.

Row
3

Ascending inner loop (j)

for (j = 1; j <= i; j++) — prints digits 1..i (left half).

Ascend
4

Descending mirror loop (k)

for (k = i - 1; k >= 1; k--) — mirrors without repeating the peak.

Mirror
5

New line

printf("\n") ends the row after both inner loops finish.

Break
=

Palindrome triangle complete

Each row mirrors itself — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, the ascending and descending halves, and the full row output.

iAscending (j)Descending (k)Row output
11(none)1
21, 21121
31, 2, 32, 112321
41, 2, 3, 43, 2, 11234321
51, 2, 3, 4, 54, 3, 2, 1123454321

Row length grows as 2i - 1 digits — total prints = for n rows.

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 k = i - 1 to k = i and watch the peak digit repeat.

2. Pattern Series Base

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

Example: continue to Program 28 for a 0-centered descending mirror variant.

3. Console Formatting Drills

Practice Write vs printf("\n") without complex math.

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

4. Spaced formatting

Add spaces between digits once the two-loop structure works.

Example: use printf("%d ", j) in both inner loops.

5. Complexity Intuition

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

Example: count printed digits for rows = 5 → 1 + 3 + 5 + 7 + 9 = 25.

6. Input Validation Labs

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

Example: reject max <= 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: trace i, j, and k on paper for rows = 3 before coding — the mirror starts at i - 1.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use j for ascending and k for descending — do not reuse the same variable for both halves.

  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 i, j, and k on Paper

    Mark the ascending half and mirror half for each row before coding.

  5. 5. Dry-Run One Small rows

    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 palindrome number triangles.

  1. 1. Newline Inside the Inner Loop

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

    → Use printf("%d", j) or printf("%d", k); printf("\n") only after both inner loops.

  2. 2. Starting Mirror at i Instead of i-1

    Starting k = i repeats the peak digit — e.g. 1221 instead of 121.

    → Use for (k = i - 1; k >= 1; k--) so the middle digit appears once.

  3. 3. Skipping the Second Loop

    Only the ascending half prints — rows look like 1, 12, 123 instead of palindromes.

    → Add the descending loop for (k = i - 1; k >= 1; k--) after the ascending loop.

  4. 4. Printing i Instead of j or k

    Writing printf("%d", i) in an inner loop repeats the row number, not the sequence digit.

    → Print j in the ascending loop and k in the descending 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 row

Output is just 1 — the mirror loop does not run.

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.

rows = 2

Smallest palindrome

Two rows: 1 and 121.

Bad input

Non-numeric scanf input

Unchecked scanf leaves rows unset — check the return value.

Large rows

Large row count

Output grows as rows² digits — fine for labs, noisy for huge values.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Diagonal asterisk

  • Descending digits with i == j swap
  • Review Program 26

2. 0-centered mirror

  • Descending mirror with leading zeros
  • Continue with Program 28

3. Spaced palindrome

  • Add printf("%d ", j) in both loops
  • Compare with Example 3 above

4. Letter palindrome

  • Print (char)('a' + j - 1) instead of digits
  • Same two-loop structure, different output

Notes

  • Mirror rule. Ascending loop prints 1..i; descending loop prints i-1..1 — start mirror at i - 1, not i.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1.
  • Add spaces with printf("%d ", j) in both loops for easier reading on wide rows.

Quick Takeaway: outer loop i = 1..rows, ascending j = 1..i, descending k = i-1..1, then printf("\n").

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Spaced output (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The palindrome number triangle is a compact lesson in symmetry: print ascending 1..i, mirror with descending i-1..1, and end each row with printf("\n"). Master the fixed-rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 28 for the 0-centered descending mirror pattern.

Start the mirror loop at i - 1, not i — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Ascend with for (j = 1; j <= i; j++)
  • Mirror with for (k = i - 1; k >= 1; k--)
  • Check scanf return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside either inner loop
  • Start the mirror loop at k = i (repeats peak)
  • Print i instead of j or k
  • Skip the descending loop entirely
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this palindrome pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

j = 1..i

Ascending

Code
+ 03

k = i-1..1

Mirror

Code
04

Palindrome

Same both ways

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Starting from i-1 avoids repeating the middle number. For example, for i=3, printing 123 then 21 makes 12321.
Use printf("%d ", j) and printf("%d ", k) in the loops instead of printf("%d", j).
The ascending loop prints 1..i and the descending loop prints i-1..1 — together they read the same forwards and backwards.
printf("%d", j) prints digits on the same line. printf("\n") ends the row after both inner loops finish.
One loop handles the ascending half (j) and the other handles the mirror half (k) — clearer than a single complex loop.
Replace 5 with rows in the outer loop bound — see Example 2.
O(n²) for n rows because row i prints 2i-1 digits and the total is 1+3+5+...+(2n-1) = n².
Check scanf's return value: if (scanf("%d", &rows) != 1) handle bad input. Unchecked scanf leaves rows uninitialized on failure.
Only one row prints — a single 1 with no mirror half.

Did you Know? 🔊

This palindrome triangle prints 1..i and then i-1..1 on each row. The second loop mirrors the first, producing outputs like 12321 and 123454321.

Continue to Program 28

Move on to the 0-centered descending mirror number pattern in the C number-pattern series.

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