Description
What is reverse number?
As number are 'reversed number' they swap places. (eg. 41 to 14)
Algorithm of a reverse number
Step 1: Read input(n)
Step 2: SET sum = 0, temp = n
Step 3: REPEAT Step 4 and Step 5 while(temp != 0)
Step 4: sum = (sum * 10) + (temp % 10)
Step 5: temp = temp/10 (REMOVE the last digit of the number)
Step 6: PRINT the REVERSE NUMBER
Step 7: Exit
Reverse a number in c programming
#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;
}
Output:
Enter the number : 7293
Reverse of 7293 is : 3927
Recommended Posts
Sum of digit calculate program
We can get the sum of the digit by adding every digits of the given number forgetting the place of value of the digit.
Program to Calculate the power of given numbers by user in c and cpp
In this program, we will take two inputs from the users, one will be the base and the another one is exponent.
Write a program to count the digit in a Number
To count the digits of a given number, divided that number by 10 until that number is greater than 0.
Insertion and Deletion of all operation at Singly Linked List in C Programming Language
Insertion and Deletion in Singly(singular) linked list in C programming langauge Data Structure. How to Implement insertion and deletion.
Simple Macro Substitution(#define) in C and C++ programming language
Program to Explain Simple Macro Substitution ( #define ) c and c++ programming language
Print numbers from 1 to 100 using while loop c and cpp program
C program to print numbers from 1 to 100 using while loop and also c++ program.