Reverse a Number Using a While Loop in C++
Reverse the digits of an integer in C++ with a while loop, % 10, and / 10. A loop-basics lesson that traces 1234 becoming 4321 one pass at a time.
1#include <iostream>2using namespace std;34int main() {5 int num, reversed = 0, remainder;67 cout << "Enter a number: ";8 cin >> num;910 int original = num;1112 while (num != 0) {13 remainder = num % 10;14 reversed = reversed * 10 + remainder;15 num /= 10;16 }1718 cout << "Reverse of " << original << " is: " << reversed << endl;1920 return 0;21}
Sample Output
Reverse of 1234 is: 4321
original is printed, then the rebuilt value.
In this one
- How a while loop runs until a condition becomes false
- How % 10 gets the last digit
- How / 10 removes the last digit
- How reversed * 10 + digit builds the new number
How it works
- 1
Read num (1234) and save a copy in original.
- 2
Loop while num != 0.
- 3
Take remainder = num % 10.
- 4
reversed = reversed * 10 + remainder.
- 5
num /= 10, then repeat until num is 0 and print.
Trace for 1234
Values at the end of each pass.
- 1.Pass 1: rem 4, reversed 4, num 123
- 2.Pass 2: rem 3, reversed 43, num 12
- 3.Pass 3: rem 2, reversed 432, num 1
- 4.Pass 4: rem 1, reversed 4321, num 0
Edge cases
Trailing zeros
Enter 1200.
The result is 21, not 0021, because an int cannot store leading zeros.
Input 0
Enter 0.
The while condition is false at once, so reversed stays 0 and the output is correct.
What's going on
This C++ program reverses the digits of an integer. 1234 becomes 4321. 100 becomes 1 — integers don't keep leading zeros.
int num, reversed = 0, remainder;
reversed starts at 0. That's the empty number you're about to build.
cin >> num;
int original = num;
Save it. The loop destroys num. Without original, the cout at the end has nothing honest to print.
while (num != 0)
Peel one digit per pass.
remainder = num % 10;
Last digit. 1234 % 10 is 4.
reversed = reversed * 10 + remainder;
Shift the digits you already have one place left, glue the new one on the right.
num /= 10;
Throw the last digit away. 1234 / 10 is 123.
Walk 1234:
100: rem 0, reversed 0, num 10 → rem 0, reversed 0, num 1 → rem 1, reversed 1. Output 1, not 001.
Negatives: % on a negative dividend is messy. This program is written for positives.
Palindrome check is this reverse, then original == reversed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
After one pass with num = 507, what are num and reversed?
Pick an answer to check it.
Question 2
What does the program print for 900?
Pick an answer to check it.
Questions people ask
Why save original?
The loop destroys num by dividing it down to 0. The copy lets you print the input at the end.
Can I reverse with a string instead?
Yes: to_string, then reverse. That keeps leading zeros but is a different exercise.
Why a while loop instead of for?
You do not know in advance how many digits there are. while keeps going until the number runs out.