Write C++ program to reverse a number using while & for loop

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
#include <math.h>
 
using namespace std;
 
int main()
{
    int num, rev = 0;
 
     //Reading a number from user
    cout<<"Enter any number:";
    cin>>num;
 
    //finding reverse number using while loop
     while (num > 0) {
      rev = rev * 10;
      rev = rev + num % 10;
      num = num / 10;
    }
 
    cout<<"Reversed number is: "<<rev;
 
    return 0;
}

Reverse a Number using for loop

#include <iostream>
#include <math.h>
 
using namespace std;
 
int main()
{
    int num, rev = 0;
 
     //Reading a number from user
    cout<<"Enter any number:";
    cin>>num;
 
    //finding reverse number using for loop
    for (rev = 0; num > 0; num = num / 10) {
      rev = rev * 10;
      rev = rev + num % 10;
    }
 
    cout<<"Reversed number is: "<<rev;
 
    return 0;
}

Result

Write C++ program to reverse a number using while & for loop
Write C++ program to reverse a number using while & for loop

Leave a Comment