Reverse-Build Number Pattern in C++

What You’ll Learn
How to print a number pattern in C++ by building the reverse of a number step-by-step and printing the partial reverse on each iteration.
This pattern is a practical way to practice digit extraction using % 10 and digit removal using / 10.
⭐ Pattern Output
For num = 86523, the output looks like this:
3
32
325
3256
32568Complete C++ Program
We repeatedly extract the last digit, append it to the reverse, print the partial reverse, and remove the last digit from the original number.
#include <iostream>
using namespace std;
int main() {
int num = 86523;
int rev = 0;
while (num != 0) {
rev = rev * 10;
rev = rev + (num % 10);
cout << rev << "\n";
num = num / 10;
}
return 0;
}🧠 How It Works
Initialize variables
num holds the source number and rev starts at 0.
Extract last digit
num % 10 gives the last digit of the current number.
Append digit to the reverse
We shift rev left with rev * 10 and add the extracted digit.
Remove last digit from the original
num /= 10 removes the last digit so the next iteration processes the next digit.
Growing reverse pattern
Each iteration adds one digit, so for a number with d digits, time complexity is O(d).
Variation — User Input Version
Read a number from the user and print the same reverse-build pattern.
#include <iostream>
using namespace std;
int main() {
long long num;
long long rev = 0;
cout << "Enter a number: ";
cin >> num;
if (num == 0) {
cout << 0 << "\n";
return 0;
}
if (num < 0) num = -num;
while (num != 0) {
rev = rev * 10 + (num % 10);
cout << rev << "\n";
num /= 10;
}
return 0;
}💡 Tips for Enhancement
Try These
- Also print the extracted digit each step using
digit = num % 10 - Store each partial reverse in a vector and print later
- Detect overflow for very large inputs (use
long longcarefully) - Try a string-based version to preserve trailing zeros
- Combine with palindrome checks using the final reverse
Avoid
- Using floating point operations for digit extraction
- Forgetting to update
numwithnum /= 10 - Printing with
endlinside the loop (unnecessary flush) - Ignoring the
num == 0case if you want 0 printed
Key Takeaways
num % 10 extracts the last digit.
rev = rev * 10 + digit appends a digit to the reverse.
The loop runs once per digit, so complexity is O(d).
This technique appears in problems like reverse numbers, digit sums, and palindromes.
❓ Frequently Asked Questions
rev. Each iteration adds one more digit to the end of rev.Explore More C++ Number Patterns!
Patterns that use digit operations are a great bridge between math and programming.
Building the reverse digit-by-digit is also used in checking whether a number is a palindrome (reads the same forwards and backwards).
12 people found this page helpful
