Write a C++ program to reverse digits of a number
Reverse number:-
Input=7890
Output=0987
Algorithm:-
Input=number reverse_number=0; while loop number > 0 (a)multiply reverse_number by 10 and add remainder of number divide by 10 to reverse_number reverse_number= reverse_number*10+number%10; (b)divide number by 10 number=number/10; print reverse_number.
Approach to solve:-
Input:num=7890
rev_num=0
rev_num=rev_num*10+num%10=0
num=num/10=789
rev_num=rev_num*10+num%10=09
num=num/10=78
rev_num=rev_num*10+num%10=098
num=num/10=7
rev_num=rev_num*10+num%10=0987
num=num/10=0
Program:-
#include<iostream>
using namespace std;
int main()
{
int num,rev_num=0;
cout<<"Enter a number:";
cin>>num;
while(num>0)
{
rev_num=rev_num*10+num%10;
num=num/10;
}
cout<<rev_num<<endl;
return 0;
}
Output:-
Enter a number:7890
0987
HAPPY CODING.......
if any query email me at:-sushank123456@gmail.com
0 comments:
Post a Comment