Rotating Number Pattern in C

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Dual Inner Loops

What You’ll Learn

The rotating number pattern prints 12345, then 23451, then 34521, … — each row starts at i and wraps back to 1 — a natural follow-up after Program 38’s decreasing-width triangle. This tutorial covers forward and wrap-around inner loops, row rotation, nested loops, a live preview, worked C examples, edge cases, and complexity.

Shape Rule

Rotating row

Row i prints i..rows, then wraps with i-1..1 — exactly rows digits per row.

Outer Loop

i = 1..rows

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

Forward Segment

i..rows

for (j = i; j <= rows; j++) — prints the increasing forward part of the row.

Wrap Segment

i-1..1

for (k = i; k > 1; k--) printf("%d", k - 1); — completes the row with wrap-around digits.

Live Preview

3–7 rows

Pick a row count and draw the rotating number pattern in the browser.

O(n²)

Complexity

Each row prints rows digits — total digits = .

Introduction

A rotating number pattern prints a circular-shift sequence on each row: 12345, then 23451, then 34521, and so on. With rows = 5, each row starts at the row number and wraps back to 1.

In C you use two inner loops per row: print printf("%d", j) from i up to rows, then print printf("%d", k - 1) from k = i down to 2, then printf("\n").

Why it matters?

It combines forward and wrap-around inner loops to build rotation — a step after Program 38’s continuous decreasing triangle.

Key Highlights

i..rows

Forward segment.

i-1..1

Wrap segment.

n digits

Per row.

Series Foundation

Follow Program 38; continue to Program 40 next.

In short: outer i = 1..rows, forward j = i..rows, wrap k = i..2 with k-1, then printf("\n").

📝 Problem & Approach

Given rows = 5, print a rotating number pattern: for each row i, print ascending i..rows then wrap with i-1..1.

c
// rows = 5
//12345
//23451
//34521
//45321
//54321

Inputs & Outputs

ItemTypeDescription
rowsintPattern height — number of rotating lines to print.
iintOuter loop — current row (1 to rows).
jintForward loop — ascending from i to rows.
kintWrap loop — descending from i to 2, prints k-1.

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
Fixed rows12345, 23451, …Learning and interviews
User-input rowsscanf("%d", &rows);Configurable pattern size
Compact tracerows = 3 on paper firstDebugging loop bounds

⚡ Quick Reference

GoalPattern
Outer loopfor (i = 1; i <= rows; i++)
Forward segmentfor (j = i; j <= rows; j++) printf("%d", j);
Wrap segmentfor (k = i; k > 1; k--) printf("%d", k - 1);
End the rowprintf("\n");
User inputscanf("%d", &rows)

📋 Fixed vs User Input vs Compact Demo

Same rotating number pattern — different ways to control the row count.

Outer loop
i = 1..rows

One rotating row per iteration

Forward
j = i..rows

Ascending segment

Wrap
k-1

i-1 down to 1

Learning tip
rows

Digits per row

Context

When This Pattern Shows Up

Reach for this pattern when teaching forward and wrap-around inner loops, circular rotation, and sequence design.

  1. After Program 38

    Natural follow-up — replaces decreasing-width rows with rotating sequences built from forward and wrap loops.

  2. Rotation drills

    Practice forward then wrap loops to build circular-shift sequences on each row.

  3. Console I/O practice

    Combine loops with scanf and return-value checks for flexible row counts.

  4. Gateway to variants

    Compare Program 37 (palindrome) and Program 40 (next in series) 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 dual inner loops, wrap-around logic, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 7 and draw the rotating number pattern in the browser.

Try 3, 5, or 7. Rows between 3 and 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print five rows of the rotating number pattern with forward and wrap-around inner loops.

Example 1 — Fixed rows = 5

Hard-coded row count — 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) {
        for (j = i; j <= rows; ++j)
            printf("%d", j);

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

        printf("\n");
    }

    return 0;
}

How It Works

When i = 3, the forward loop prints 3 4 5, the wrap loop prints 2 1 — output 34521. When i = 1, only the forward loop runs — output 12345.

📈 User Input

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

Example 2 — User input rows

Read rows with scanf("%d", &rows) and validate the return value.

c
#include <stdio.h>

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

    printf("Enter rows: ");
    if (scanf("%d", &rows) != 1 || rows < 1) return 0;

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

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

        printf("\n");
    }

    return 0;
}

How It Works

Same rotating core as Example 1; only rows comes from user input instead of being hard-coded as 5. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Smaller Demo

Run with rows = 3 to trace every row on paper before scaling up.

Example 3 — Compact rows = 3

Same forward and wrap loops with a smaller row count for quick tracing.

c
#include <stdio.h>

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

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

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

        printf("\n");
    }

    return 0;
}

How It Works

Only rows changes from 5 to 3 — the two inner loops stay identical. Trace i = 1, 2, 3 on paper to see how each row rotates the sequence.

🧠 How the Algorithm Prints Rows

1

Set up

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

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — ascending outer loop; one rotating row per iteration.

Row
3

Forward segment

for (j = i; j <= rows; j++) — prints i, i+1, ..., rows.

Forward
4

Wrap segment

for (k = i; k > 1; k--) — prints i-1, i-2, ..., 1 via k-1.

Wrap
5

New line

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

Break
=

Rotating pattern complete

Each row prints exactly rows digits — total digits = ; O(n²) time.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, forward and wrap segments, and full row output.

iForward (i..rows)Wrap (i-1..1)Row output
11, 2, 3, 4, 512345
22, 3, 4, 5123451
33, 4, 52, 134521
44, 53, 2, 145321
554, 3, 2, 154321

Each row prints exactly rows digits — total digits = n × n = n².

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: swap forward and wrap loops and watch the rotation break.

2. Pattern Series Base

Foundation for rotation-based patterns and circular-shift sequences.

Example: compare with Program 38 (decreasing) and Program 40 next.

3. Console Formatting Drills

Practice concatenated digit output without spaces between numbers.

Example: add j + " " between digits for a spaced rotation variant.

4. Alphabet rotation

Swap digits for letters once the two-loop structure works.

Example: print (char)('A' + j - 1) for an A..E rotation pattern.

5. Complexity Intuition

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

Example: count digits for rows = 5 — total is 5×5 = 25 = 5².

6. Input Validation Labs

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

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: trace i, forward segment j = i..rows, and wrap segment on paper for rows = 3 before coding.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Inner Loops Per Row

    Forward loop (j <= rows) must run before wrap loop (k > 1).

  2. 2. Check scanf return value

    Avoid undefined behavior when the user types letters instead of a number.

  3. 3. Keep newline outside inner loops

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

  4. 4. Trace segments on Paper

    Write forward (i..rows) and wrap (i-1..1) for each row before coding.

  5. 5. Dry-Run rows = 3

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

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

Common Pitfalls

Mistakes that commonly break rotating number patterns.

  1. 1. Newline Inside an Inner Loop

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

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

  2. 2. Wrong Loop Order

    Running wrap before forward breaks the rotation sequence.

    → Always print forward j = i..rows first, then wrap k = i..2 with k-1.

  3. 3. Wrong Wrap Bound

    Using k >= 1 and printing k duplicates the start digit.

    → Keep for (k = i; k > 1; k--) printf("%d", k - 1); — stop at 2, print k-1.

  4. 4. Printing k Instead of k-1

    Printing k in the wrap loop shifts the wrap segment by one.

    → Use printf("%d", k - 1) so wrap prints i-1..1.

  5. 5. Blind scanf

    Letters or empty input leave rows uninitialized or unchanged.

    → 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 — only the forward loop runs.

rows = 0

Empty pattern

Outer loop never runs when rows < 1 — print nothing or show a message.

Negative

rows < 1

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

rows = 2

Smallest pattern

Two rows: 12 and 21.

Bad input

Non-numeric scanf input

scanf without a return check is unsafe — validate input.

Large rows

Large row count

Total digits = rows² — each row prints rows digits.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Decreasing-width triangle

  • Review Program 38
  • Continuous counter with shrinking row width

2. Next in series

  • Continue with Program 40
  • Next pattern in the number-pattern series

3. Rotation trace

  • Prove on paper: row i always prints rows digits
  • Forward = i..rows, wrap = i-1..1

4. Safe input loop

  • Check scanf return value until rows >= 1
  • Then draw the triangle

Notes

  • Rotation rule. Outer i = 1..rows. Forward j = i..rows, then wrap k = i..2 with k-1 — row i prints exactly rows digits.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate rows >= 1 for interactive programs; rows = 1 prints a single 1.
  • When i = 1, the wrap loop does not run — compare with Program 37 where each row is a palindrome.

Quick Takeaway: outer i = 1..rows, forward j = i..rows, wrap k = i..2 with k-1, then printf("\n").

⏱️ Time and Space Complexity

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

🎉 Conclusion

The rotating number pattern is a compact lesson in wrap-around logic: print forward i..rows, then wrap with k-1 from k = i..2, and end each row with printf("\n"). Master the fixed-rows version, then try user input and a smaller trace demo.

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

Forward loop must run before wrap loop — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Forward: for (j = i; j <= rows; j++) printf("%d", j);
  • Wrap: for (k = i; k > 1; k--) printf("%d", k - 1);
  • Check scanf return value instead of ignoring bad input
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call printf("\n") inside an inner loop
  • Run wrap loop before forward loop
  • Print k instead of k-1 in the wrap loop
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this rotating pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

k-1 wrap

i-1..1

Code
0 03

n digits

Per row

Code
04

Row break

printf("\n") after both inner loops

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

For 5 rows: 12345, 23451, 34521, 45321, 54321 — each row starts at the row number and wraps back to 1.
The first loop prints i..rows (forward segment). The second loop prints i-1 down to 1 (wrap segment). Together they always produce rows digits.
After printing 2 3 4 5, the wrap loop prints k-1 when k runs from i down to 2 — for i=2 that prints 1.
Exactly rows digits every time — (rows - i + 1) forward plus (i - 1) wrap = rows.
Program 37 builds palindrome rows (i..2 then 1..i). Program 39 rotates: i..rows then i-1..1.
Replace 5 with rows in the outer loop bound — see Example 2.
O(n²) for n rows because each row prints n digits.
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 digit 1.

Did you Know? 🔊

Each row starts at i, prints i..rows, then wraps with i-1..1. Row i always prints exactly rows digits — total digits = .

Continue to Program 40

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

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