Header Ads Widget

C++ program to reverse a number

 

 C++ program  to reverse a number

Given a number , write a C++ program to reverse a number . So for doing this first we will find the reminder by dividing number by 10 and take a variable let's rev_num and initialize it with 0 . Each time multiply it by 10 and add the reminder to it . For better understanding see the sample input and output .

Sample input 

123

Sample output

321

Explanation:  

num=123 and rev_num=0
1. r=123%10 = 3
rev_num=0*10+3 = 3
num=123/10 = 12
2. r=12%10 = 2
rev_num=3*10+2 = 32
num=12/10 = 1
3. r=1%10 = 1
rev_num=32*10+1 = 321
num=1/10 = 0

 C++ program  to reverse a number

The objective of the code is to reverse the number  in C++ .

Code(C++):-

#include <iostream>
using namespace std;
int main()
{
int num,rev_num=0,r,tem;
cout<<"Enter a number\n";
cin>>num;
tem=num;
while(num!=0)
{
r=num%10;
rev_num=rev_num*10+r;
num/=10;
}
cout<<"Reverse of number "<< tem<<" is "<<rev_num;
return 0;
}


Output:-

Enter a number
123
Reverse of number 123 is 321

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments