Monday, 16 June 2014

C++ program to reverse a number

C++ program to find reverse of a given number. Here you will find different methods to reverse a number.


Method 1 : C++ program to reverse a number
#include<iostream>
using namespace std;
int main()
{
    int num;
    cout<<"Enter the number ";
    cin>>num;
    cout<<"Reverse of the number ";
    while(num!=0)
    {
        cout<<num%10;
        num/=10;
    }
    return 0;
}




Method 2 : C++ program to store reverse of a number in another variable
#include<iostream>
using namespace std;
int main()
{
    int num,rev,temp=0;
    cout<<"Enter the number ";
    cin>>num;
    while(num!=0)
    {
        temp*=10;
        temp+=num%10;
        num/=10;
    }
    cout<<"Reverse of the number : "<<temp;
    return 0;
}




Method 3 : C++ program to reverse a number using recursion
#include<iostream>
using namespace std;
void rev(int n)
{
    if(n==0)
        return ;
    cout<<n%10;
    rev(n/10);
}
int main()
{
    int n;
    cout<<"Enter number : ";
    cin>>n;
    cout<<"Reverse of the number is : ";
    rev(n);
    return 0;
}


No comments:

Post a Comment