As number are reversed number they swap places. (e.g. 41 to 14).
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter the number : ");
scanf("%d", &n);
int temp = n;
while(temp!=0){
reverse = (reverse*10) + (temp%10);
temp = temp / 10;
}
printf("Reverse of %d is : %d", n, sum);
return 0;
}
This program takes input from the user. Then the while loop is start until the (temp ≠ 0) is false.
In each iteration of the loop,
Let's see, n = 234, temp = n = 234.
STEP 1: Initially temp is 234, check the condition (234 ≠ 0), condition true, now reverse = (0 * 10) + (234 % 10) = 0 + 4 = 4. Reverse 4, temp = temp / 10 = 234 / 10 = 23. temp = 23.
STEP 2: Now temp is 23, check the condition (23 ≠ 0), condition true, now reverse = (4 * 10) + (23 % 10) = 40 + 3 = 43. Reverse 43, temp = temp / 10 = 23 / 10 = 2. temp = 2.
STEP 3: Now temp is 2, check the condition (2 ≠ 0), condition true, now reverse = (43 * 10) + (2 % 10) = 430 + 2 = 432. Reverse 432, temp = temp / 10 = 2 / 10 = 0. temp = 0.
STEP 4: Now temp is 0, check the condition (0 ≠ 0), condition false, now the loop is terminated.
Finally, the reverse variable (which contains the reversed number) is print on the terminal.
// C++ program to reverse a number
#include <iostream>
using namespace std;
int main()
{
int n, reverse = 0;
cout<<"Enter the number : ";
cin>>n;
int temp = n;
while(temp!=0){
reverse = (reverse*10) + (temp%10);
temp = temp / 10;
}
cout<<"Reverse of "<<n<<" is : "<<reverse;
return 0;
}
Comments
Oops!