Number Pattern by Removing Last Digit in C++

What You’ll Learn
How to print a number pattern by repeatedly removing the last digit of an integer in C++.
This uses a simple while loop plus integer division: num = num / 10.
⭐ Pattern Output
For num = 86523, the output looks like this:
86523
8652
865
86
8Complete C++ Program
We print the current number, then remove the last digit by dividing by 10 until the number becomes 0.
#include <iostream>
using namespace std;
int main() {
int num = 86523;
while (num != 0) {
cout << num << "\n";
num = num / 10;
}
return 0;
}🧠 How It Works
Start with a number
int num = 86523; is the value we want to shorten step by step.
Loop until it becomes 0
while (num != 0) keeps running as long as there is at least one digit left.
Print then remove last digit
We print num, then update it with num = num / 10, which removes the last digit via integer division.
Stop naturally
Eventually, dividing by 10 makes the value 0, the condition fails, and the loop ends.
Digit-removal pattern
If the number has d digits, the loop runs d times, so the time complexity is O(d).
Variation — User Input Version
Read a number from the user and print the same digit-removal pattern.
#include <iostream>
using namespace std;
int main() {
long long num;
cout << "Enter a number: ";
cin >> num;
if (num == 0) {
cout << 0 << "\n";
return 0;
}
if (num < 0) num = -num;
while (num != 0) {
cout << num << "\n";
num /= 10;
}
return 0;
}💡 Tips for Enhancement
Try These
- Print the removed digit each step using
num % 10 - Count how many steps were printed (digit count)
- Extend it to print prefixes left-to-right using strings
- Handle negative values by printing the sign separately
- Validate input with
cin.fail()for robustness
Avoid
- Using floating-point division (you want integer division)
- Forgetting to update
numinside the loop - Printing with
endlin tight loops (slower) - Ignoring the
num == 0case if you want 0 printed
Key Takeaways
Integer division by 10 removes the last digit of a number.
A while loop is ideal when you don’t know the number of steps in advance.
The number of printed lines equals the number of digits, so complexity is O(d).
This digit logic is also useful for reversing numbers and digit-sum problems.
❓ Frequently Asked Questions
num % 10 before doing num /= 10.Explore More C++ Number Patterns!
Keep practicing with loop-based patterns to build strong fundamentals.
Digit trimming is the basis for many classic tasks like reversing a number, checking palindromes, and extracting digits one by one.
12 people found this page helpful
