Progressive Reverse-Build Number Pattern in Java

Beginner
⏱️ 7 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo + Division

What You’ll Learn

This pattern builds the reverse of a number step by step, printing after each digit append. Starting from num = 86523: 3, 32, 325, 3256, 32568. Use num % 10 to extract digits and num / 10 to shrink the source. This tutorial covers the loop logic, live preview, worked Java examples, edge cases, and O(d) complexity.

Extract Digit

num % 10

Modulo gets the last digit: 86523 % 10 → 3.

Append to Reverse

reverse * 10 + digit

Shift reverse left and add the digit: 0 → 3 → 32 → 325.

Print Reverse

println(reverse)

Each iteration prints the growing reverse value.

After Program 60

% 10 + / 10

Natural next step — Program 60 printed num; this builds reverse.

Live Preview

Any integer

Enter a starting number and see each progressive reverse line instantly.

O(d)

Complexity

One iteration per digit — linear in the number of digits.

Introduction

A progressive reverse-build pattern appends the last digit of num to a running reverse value and prints it each step.

In Java: while (num != 0), update reverse = reverse * 10 + (num % 10), print reverse, then num = num / 10.

Why it matters?

Pairing % 10 and / 10 is the core technique for reversing numbers, counting digits, and checking palindromes — the natural follow-up to Program 60.

Key Highlights

Modulo %10

num % 10 extracts the last digit each step.

Build reverse

reverse * 10 + digit appends to the right.

vs Program 60

Program 60 printed num; this prints growing reverse.

O(d) time

Runs once per digit — very efficient.

In short: while num != 0, append num % 10 to reverse, print reverse, then num = num / 10.

📝 Problem & Approach

Given num = 86523, build and print reverse after each digit is appended: 3, 32, 325, 3256, 32568.

Java
int num = 86523;
int reverse = 0;
while (num != 0) {
    reverse = reverse * 10 + (num % 10);
    System.out.println(reverse);
    num = num / 10;
}

Inputs & Outputs

ItemTypeDescription
numintStarting positive integer — loop runs while num != 0.
reverseintRunning reverse built with reverse * 10 + (num % 10).
Printed outputtextOne line per iteration — growing reverse: 3, 32, 325, 3256, 32568.

Minimal workflow

Pseudocode
reverse = 0
while num != 0:
    reverse = reverse * 10 + (num % 10)
    print reverse
    num = num / 10

Approach comparison

ApproachIdeaBest for
While + moduloreverse * 10 + num % 10Classic reverse build — Example 1
Scanner inputsc.nextInt() for numUser-chosen starting number
long accumulatorlong reverse for large inputsOverflow-safe variant — Example 3
Program 60 contrastPrint num then /10Removes digits instead of building reverse

⚡ Quick Reference

GoalPattern
Init accumulatorint reverse = 0;
Loop conditionwhile (num != 0)
Extract last digitnum % 10
Append to reversereverse = reverse * 10 + (num % 10);
Print progressive lineSystem.out.println(reverse);
Shrink numnum = num / 10;

📋 Modulo Build vs Print num vs long

Three teaching angles — progressive reverse build (this program), digit removal (Program 60), and overflow-safe long.

Modulo + build
reverse = reverse * 10 + num % 10

Core pattern for Examples 1 and 2.

Program 60
println(num); num /= 10

Prints shrinking num instead of growing reverse.

long reverse
long reverse = 0;

Safer for very large inputs — Example 3.

Learning tip
build, print, then /10

Update reverse and print before dividing num.

Context

When This Pattern Shows Up

Use progressive reverse-build when teaching modulo, digit extraction, and partial reverse snapshots in one while loop.

  1. After Program 60

    Natural next step once students can divide by 10 — now combine with % 10.

  2. Reverse-number drills

    Print intermediate reverses before the classic single-line reverse program.

  3. Console I/O practice

    Pair with Scanner — see Example 2.

  4. Gateway to spirals

    Continue to Program 62 (Perfect Square Spiral) after mastering digit loops.

  5. Not a UI layout tool

    Console teaching pattern — builds algorithmic thinking, not screen layouts.

Key benefit: one loop that connects modulo, multiply-by-10, and progressive output.

🔮 Live Preview

Enter a starting number and see each progressive reverse-build line.

Try 86523, 12345, or 987654.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed num = 86523, Scanner input, and a long overflow-safe variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five progressive reverse lines from 86523: 3, 32, 325, 3256, 32568.

Example 1 — Fixed num = 86523

Build reverse digit by digit and print after each append.

Java
public class ProgressiveReverseBuildPattern {
    public static void main(String[] args) {
        int num = 86523;
        int reverse = 0;

        while (num != 0) {
            reverse = reverse * 10 + (num % 10);
            System.out.println(reverse);
            num = num / 10;
        }
    }
}

How It Works

First iteration takes digit 3, sets reverse to 3, then num becomes 8652. Each step appends the next last digit until num is 0.

📈 Practical Variant

Read the starting number with Scanner.

Example 2 — Scanner Input

Same reverse-build loop; starting number comes from user input.

Java
import java.util.Scanner;

public class ProgressiveReverseBuildInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        int reverse = 0;

        while (num != 0) {
            reverse = reverse * 10 + (num % 10);
            System.out.println(reverse);
            num = num / 10;
        }

        sc.close();
    }
}

How It Works

Same progressive reverse build as Example 1; only the source of num changes.

⚡ Overflow-Safe Variant

Use long for reverse when inputs may be large.

Example 3 — long Accumulator

Identical logic with long reverse to reduce overflow risk on big numbers.

Java
public class ProgressiveReverseBuildLong {
    public static void main(String[] args) {
        long num = 86523L;
        long reverse = 0L;

        while (num != 0) {
            reverse = reverse * 10L + (num % 10L);
            System.out.println(reverse);
            num = num / 10L;
        }
    }
}

How It Works

long widens the range for reverse as it grows — same output for classroom-sized inputs like 86523.

🧠 How Progressive Reverse-Build Works

1

Init reverse = 0

int reverse = 0; and int num = 86523; before the loop.

Setup
2

Extract digit with %10

num % 10 reads the last digit (3, then 2, then 5, …).

Modulo
3

Append reverse * 10 + digit

reverse = reverse * 10 + (num % 10); grows the reverse on the right.

Build
4

Print reverse

System.out.println(reverse); shows 3, 32, 325, 3256, 32568.

Print
5

Divide num / 10

num = num / 10; removes the processed digit and moves to the next.

Divide
=

Progressive reverse complete

Exactly d lines for d digits — O(d) time, O(1) extra space.

🔎 Worked Walkthrough — num = 86523

Trace each loop iteration: extract digit, update reverse, print, then divide.

Stepnumdigitreverse printednum after /10
186523338652
28652232865
3865532586
486632568
588325680 (loop ends)

The loop stops when num becomes zero after the fifth division.

Use Cases

Where progressive reverse-build and digit-manipulation loops show up in Java courses.

1. Full Number Reverse

Same loop structure prints only the final reverse instead of each step.

Example: move println outside the loop to print only the final reverse.

2. Palindrome Check

Combine % 10 and / 10 to build a reversed half for comparison.

Example: compare digits from both ends using modulo and division.

3. Count Digits

Same /10 loop counts how many digits a number has.

Example: increment a counter each iteration until num is 0.

4. Program 60 Contrast

Program 60 printed shrinking num; this prints growing reverse.

Example: compare both outputs side by side from the same starting value.

5. O(d) Complexity

Linear in digit count — much faster than grid patterns for large numbers.

Example: 86523 has 5 digits → 5 loop iterations.

6. Input Validation

Pair with Scanner and reject zero or negative input if required.

Example: use sc.hasNextInt() before reading input.

Pro Tip: always update and print reverse before dividing num — dividing first skips the current digit.

Advantages

Why progressive reverse-build belongs in beginner Java courses.

  1. 1. One Simple Loop

    No nested loops — natural follow-up to Program 60’s digit-removal loop.

  2. 2. Teaches Modulo + Build

    num % 10 and reverse * 10 + digit are core reverse tools.

  3. 3. Easy to Extend

    Try Scanner input, long variant, or continue to Program 62.

  4. 4. O(1) Extra Memory

    Only one integer variable changes — no arrays needed.

Pro Tip: trace 86523 on paper — five lines, five digit appends, then stop.

Usage Tips

Small habits that keep reverse-build code correct.

  1. 1. Append Before Divide

    Always update and println(reverse) first, then num = num / 10.

  2. 2. Use Integer Division

    Keep num as int — floating-point division breaks digit removal.

  3. 3. Loop Until Zero

    while (num != 0) stops when the last digit has been appended, printed, and divided away.

  4. 4. Handle Zero Input

    If num starts at 0, the loop never runs — validate or show a message.

  5. 5. Try num /= 10

    Compound assignment is equivalent to num = num / 10.

Pro Tip: if the first line is wrong, you divided before appending the digit to reverse.

Common Pitfalls

Mistakes that commonly break progressive reverse-build patterns.

  1. 1. Dividing Before Updating reverse

    First line shows 32 instead of 3 — you divided before appending the current digit.

    → Update reverse and print first, then divide.

  2. 2. Infinite Loop

    Forgetting num = num / 10 leaves num unchanged forever.

    → Always update num inside the loop body.

  3. 3. Floating-Point Division

    Using double can introduce precision issues on very large values.

    → Use int or long for clean digit removal.

  4. 4. Unchecked Scanner Input

    Letters or empty input leave num uninitialized.

    → Call sc.hasNextInt() before nextInt().

  5. 5. Starting num at 0

    while (num != 0) never executes — no output at all.

    → Validate input or show a message when num is 0.

Edge Cases

Check these inputs before calling the solution done.

num = 0

Zero input

Loop never runs — print nothing or show a message.

Single digit

num = 8

Output is one line: 8 — then num becomes 0.

Trailing zero

num = 120

Prints 120 then 12 then 1 — zero drops immediately.

Negative

Trailing zeros in input

Use Math.abs(num) first for clean positive output.

Bad input

Non-numeric Scanner input

Call sc.hasNextInt() before reading num.

Large num

Large values

Use long if values exceed Integer.MAX_VALUE.

🎯 Practice Problems

Try these variations to lock in progressive reverse-build.

1. Change starting number

  • Try 12345, 999, or 120
  • Count how many lines print

2. Print only final reverse

  • After the loop, print reverse once without intermediate lines
  • Compare with the progressive print version

3. long variant

  • Rewrite with long reverse — Example 3
  • Confirm output matches the int version for 86523

4. Next in series

  • Continue with Program 62
  • Perfect Square Spiral after digit-loop mastery

Notes

  • Digit count. Loop runs once per digit — O(d) time for d digits.
  • % 10 extracts the last digit; / 10 removes it — pair them in every reverse-build loop.
  • Validate num != 0 for interactive programs; zero input prints nothing.
  • Compare with Program 60 (prints shrinking num) — this pattern prints growing reverse.

Quick Takeaway: append num % 10 to reverse, print reverse, then num = num / 10, repeat while num != 0.

⏱️ Time and Space Complexity

ProgramTimeExtra space
While loop (Examples 1–2)O(d)O(1)
long variant (Example 3)O(d)O(1)
Wrap Up

🎉 Conclusion

The progressive reverse-build pattern is a compact while-loop lesson: extract the last digit, append to reverse, print, divide by 10, repeat until zero. Master the fixed-num version, then try Scanner input and the long variant in Example 3.

Practice the three examples above, then continue to Program 62 for the Perfect Square Spiral pattern.

Build then print — loop while num != 0 — O(d) time for d digits.

💡 Best Practices

✅ Do

  • Update and print reverse before num = num / 10
  • Use while (num != 0) as the loop condition
  • Validate non-zero input for interactive programs
  • Call sc.hasNextInt() before using Scanner input
  • State O(d) time when asked about complexity

❌ Don’t

  • Divide before updating reverse
  • Forget to update num inside the loop
  • Use floating-point types for reverse build
  • Ignore zero input in user-facing demos
  • Skip the single-digit edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about progressive reverse-build

One while loop, modulo append, O(d) time.

5
Core concepts
02

While loop

num != 0

Code
/ 03

Modulo

num % 10

Code
04

Prints each step

d lines for d digits

Edge
O 05

Complexity

O(d) time

Analysis

❓ Frequently Asked Questions

Because 3 is the last digit of 86523. The program takes num % 10 first and appends it to reverse.
Each step appends the next last digit to reverse: 3, then 2 → 32, then 5 → 325, then 6 → 3256.
Once all digits of 86523 are processed, reverse becomes 32568 and num becomes 0, ending the loop.
Related — you build the reverse but print it after every step rather than only the final reverse.
Trailing zeros become leading zeros in the reverse, but leading zeros are not shown in integer printing.
Yes. Use Scanner.nextInt() and the same loop — see Example 2.
O(d) where d is the number of digits — one loop iteration per digit.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Each step appends the last digit of num to reverse with reverse = reverse * 10 + (num % 10), then shrinks num with / 10. From 86523: 3, 32, 325, 3256, 32568O(d) time.

Continue to Program 62

Move on to the Perfect Square Spiral pattern in the Java number-pattern series.

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