Remove-Last-Digit Number Pattern in Java

Beginner
⏱️ 7 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
While Loop /10

What You’ll Learn

This pattern prints a number, then repeatedly removes the last digit with integer division by 10. Starting from 86523: 86523, 8652, 865, 86, 8. A single while loop handles it — no nested loops needed. This tutorial covers the loop logic, live preview, worked Java examples, edge cases, and O(d) complexity.

Print First

println(num)

Each iteration prints the current value before shrinking it.

Divide by 10

num / 10

Integer division drops the last digit: 86523 → 8652.

While Loop

num != 0

Loop runs once per digit until the number becomes zero.

After Grid Patterns

Program 59

Natural break from nested loops — one variable, one while loop.

Live Preview

Any integer

Enter a starting number and see each digit-removal line instantly.

O(d)

Complexity

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

Introduction

A remove-last-digit pattern prints a number line by line, dropping the rightmost digit each time using num / 10.

In Java: while (num != 0), print num, then num = num / 10 until the value reaches zero.

Why it matters?

Integer division by 10 is the foundation for digit counting, reversing numbers, and palindrome checks — a natural step after grid patterns in Program 59.

Key Highlights

One loop

No nested loops — a single while suffices.

/ 10 trick

Integer division removes the last digit each step.

vs Program 61

Program 61 builds the reverse progressively with % 10.

O(d) time

Runs once per digit — very efficient.

In short: while num != 0, print num, then set num = num / 10.

📝 Problem & Approach

Given starting number num = 86523, print each value as you remove the last digit until the number becomes zero.

Java
// num = 86523 (conceptual output)
// 86523
// 8652
// 865
// 86
// 8

Inputs & Outputs

ItemTypeDescription
numintStarting positive integer — must be non-zero for the loop to run.
Loop conditionbooleanwhile (num != 0) — stops when division reaches zero.
Printed outputtextOne line per iteration — full number, then number minus last digit, and so on.

Minimal workflow

Pseudocode
while num != 0:
    print num
    num = num / 10

Approach comparison

ApproachIdeaBest for
While + divisionnum / 10 each iterationClassic digit-removal — Example 1
Scanner inputsc.nextInt() for numUser-chosen starting number
String substrings.substring(0, len)String practice — Example 3
Compound assignnum /= 10Shorter equivalent to num = num / 10

⚡ Quick Reference

GoalPattern
Set starting numberint num = 86523;
Loop conditionwhile (num != 0)
Print current valueSystem.out.println(num);
Remove last digitnum = num / 10; or num /= 10;
Handle negativesnum = Math.abs(num); before the loop
Program 61 contrastProgram 61 uses % 10 to build reverse progressively

📋 Division vs String vs Modulo

Three ways to work with digits — this pattern uses division; Program 61 uses modulo.

Division /10
num = num / 10

Removes last digit — used in Examples 1 and 2.

Modulo %10
digit = num % 10

Extracts last digit — used in Program 61 reverse build.

String slice
s.substring(0,len)

Same visual output without arithmetic — Example 3.

Learning tip
print then divide

Always print before dividing — otherwise you skip the first value.

Context

When This Pattern Shows Up

Reach for this pattern when teaching while loops, integer division, and digit manipulation without nested loops.

  1. After grid patterns

    Natural break from nested loops in Program 59 — one variable, one while loop.

  2. While-loop practice

    Simple loop condition with a clear stopping point when num reaches zero.

  3. Console I/O practice

    Read starting number with Scanner — see Example 2.

  4. Gateway to variants

    Compare with Program 61 (reverse build with % 10), then continue the digit series.

  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 while loops, integer division, and O(d) digit thinking.

🔮 Live Preview

Enter a starting number and see each digit-removal line in the browser.

Try 86523, 12345, or 987654.

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print five lines from 86523 down to 8 using a while loop.

Example 1 — Fixed num = 86523

Print the current value, then divide by 10 until the number becomes zero.

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

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

How It Works

First iteration prints 86523, then num becomes 8652. Each step removes one digit until num is 0 and the loop exits.

📈 Practical Variant

Read the starting number with Scanner.

Example 2 — Scanner Input

Same while-loop logic; starting number comes from user input.

Java
import java.util.Scanner;

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

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

        sc.close();
    }
}

How It Works

Same digit-removal loop as Example 1; only the source of num changes.

⚡ String Variant

Same output using String.substring instead of division.

Example 3 — String Substring Approach

Convert to string and print progressively shorter prefixes.

Java
public class RemoveLastDigitString {
    public static void main(String[] args) {
        int num = 86523;
        String s = String.valueOf(num);

        for (int len = s.length(); len >= 1; len--) {
            System.out.println(s.substring(0, len));
        }
    }
}

How It Works

substring(0, len) prints prefixes of decreasing length — same visual result without / 10.

🧠 How the Algorithm Removes Digits

1

Set starting number

int num = 86523; — the value printed on the first line.

Setup
2

Loop while num != 0

while (num != 0) runs once per digit until division reaches zero.

Loop
3

Print current value

System.out.println(num) outputs the current line before shrinking.

Print
4

Divide by 10

num = num / 10 drops the last digit: 86523 → 8652 → 865 → 86 → 8.

Divide
=

Digit-removal sequence complete

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

🔎 Worked Walkthrough — num = 86523

Trace each loop iteration: print, then divide by 10.

StepPrintAfter num / 10
1865238652
28652865
386586
4868
580 (loop ends)

Zero is never printed because the loop condition is checked before the next iteration.

Use Cases

Where integer division by 10 shows up beyond this homework pattern.

1. Count Digits

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

Example: loop until num=0 and count iterations.

2. Reverse a Number

Combine % 10 and / 10 — see Program 61.

Example: extract last digit with modulo, shrink with division.

3. Palindrome Check

Build reversed half while dividing — classic interview prep.

Example: compare original with reversed digits.

4. String Alternative

Same output with substring — see Example 3.

Example: no arithmetic, just shorter string prefixes.

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: re-prompt when user enters 0.

Pro Tip: always print before dividing — dividing first skips the original value on the first line.

Advantages

Why this pattern earns a spot in beginner Java courses.

  1. 1. One Simple Loop

    No nested loops — easier than grid patterns in Program 59.

  2. 2. Teaches Integer Division

    / 10 and % 10 are core digit-manipulation tools.

  3. 3. Easy to Extend

    Try string variant, negative handling, or continue to Program 61.

  4. 4. O(1) Extra Memory

    Only one integer variable changes — no arrays needed.

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

Usage Tips

Small habits that keep digit-removal code correct.

  1. 1. Print Before Divide

    Always println(num) 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 single digit has been printed and divided.

  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 output is missing the first number, you divided before printing.

Common Pitfalls

Mistakes that commonly break digit-removal patterns.

  1. 1. Dividing Before Printing

    First line shows 8652 instead of 86523 — you skipped the original value.

    → Print num 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

Negative num

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 the pattern.

1. Change starting number

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

2. Print removed digits

  • Use num % 10 before dividing
  • Show which digit was dropped each step

3. String variant

  • Rewrite with substring — Example 3
  • Compare output with division version

4. Next in series

  • Continue with Program 61
  • Progressive reverse build from same number

Notes

  • Digit count. Loop runs once per digit — O(d) time for d digits.
  • / 10 removes last digit; % 10 extracts it — pair them in Program 61.
  • Validate num != 0 for interactive programs; zero input prints nothing.
  • Compare with Program 59 (nested grid loops) — this pattern needs only one while loop.

Quick Takeaway: print num, then num = num / 10, repeat while num != 0.

⏱️ Time and Space Complexity

ProgramTimeExtra space
While loop (Examples 1–2)O(d)O(1)
String substring (Example 3)O(d²)O(d) for string
Wrap Up

🎉 Conclusion

The remove-last-digit pattern is a compact while-loop lesson: print the value, divide by 10, repeat until zero. Master the fixed-num version, then try Scanner input and the string variant in Example 3.

Practice the three examples above, then continue to Program 61 for the progressive reverse-build pattern.

Print before divide — loop while num != 0 — O(d) time for d digits.

💡 Best Practices

✅ Do

  • Print num 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 printing the current value
  • Forget to update num inside the loop
  • Use floating-point types for digit removal
  • Ignore zero input in user-facing demos
  • Skip the single-digit edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this digit-removal pattern

One while loop, integer division, O(d) time.

5
Core concepts
02

While loop

num != 0

Code
/ 03

Division

num / 10

Code
04

Stops at 0

Zero not printed

Edge
O 05

Complexity

O(d) time

Analysis

❓ Frequently Asked Questions

Integer division discards the remainder. So 86523/10 becomes 8652, 8652/10 becomes 865, and so on.
The loop prints num then divides. When num becomes 0, while (num != 0) is false — 0 is never printed.
Yes, but use Math.abs(num) first so output has no leading minus on every line.
Yes. Convert to String and print substring(0, len) — see Example 3.
120/10 becomes 12 immediately — trailing zeros drop like any other last digit.
Yes. Use Scanner.nextInt() and the same while-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? 🔊

Integer division by 10 drops the last digit each step — 86523 becomes 8652, then 865, 86, 8. One while loop, O(d) time for d digits.

Continue to Program 61

Move on to the progressive reverse-build number pattern in the Java number-pattern series.

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