How to write C++ program to Reverse a Number | Virtual Study Solutions

Adsetra Ads

 

How to write C++ program to Reverse a Number

Dear Students, Today in C++ Programming Tutorial we will learn How to write C++ program to Reverse a Number. It is a very simple C++ program in which user enter a number, program reverse it and display reversed number on the console.
For example:
If input number is 12345
Reversed number will be 54321

How to write C++ program to Reverse a Number
How to write C++ program to Reverse a Number
Programming Concept used: for loop, modulus operator

In this Tutorial we will discuss following points below given:
  1. Logic making and explanation
  2. C++ Program Code 
  3. Image view of Program Code
  4. Sample Output of Program Code
  5. Explanation of Program to Reverse a Number

1 - C++ program Logic Explanation:

  • If you want to make a c++ program like that we need to access every digit individually of entered number from last.
  • Modulus operator provides such condition so first we take modulus of number until it become zero and add the every single digit which produce by modulus operator into our new integer variable which is named as reverse in the program with at each iteration of for loop
  • When for loop is break variable revers will have the reverse of entered number

2 - Program Code

#include<iostream>
using namespace std;

int main() {
int number, reverse = 0;
cout<<"Input a Number to Reverse and press Enter: ";
cin>> number; // Taking Input Number in variable number

for( ; number!= 0 ; )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
cout<<"New Reversed Number is: "<<reverse;
return 0;

}

Note : We can also use while(number!=0) instead of for( ; number!=0 ; )

Image view of Program code:


Sample Output of Program Code:


Explanation of Program to Reverse a Number

Let input number is 123
so number=123 and reverse=0

number!=0 for loop condition true
reverse = reverse * 10; reverse=0
reverse = reverse + number%10; reverse= 0 + 123%10= 3
number = number/10; number=123/10= 12

number=12 for loop condition(number!=0) true
for loop iteration
reverse = 3 * 10; reverse=30
reverse = reverse + number%10; reverse= 30 + 12%10= 32
number = number/10; number=12/10= 1

number=1 for loop condition(number!=0) true
for loop iteration reverse = reverse * 10; reverse=320
reverse = reverse + number%10; reverse= 320 + 1%10= 321
number = number/10; number=1/10= 0


Note : number=0 for loop condition false loop will break and display the output value of reverse.

Recommended C++ Programs.

How to write C++ program to find Fibonacci Series

How to Write C++ Program to Find Prime Number

How to write C++ Program to find factorial of Number

If You liked this Programming Tutorial Please share with your friends. Like us on Facebook and Subscribe us below for More Interesting Tutorials. Thanks

Post a Comment

 

Top