Que) Write C++ Program to Reverse the Number.

 Solution:

               #include <iostream>

                using namespace std;


               int main() {

               int n,remainder,reverse_no=0;

               cout<<"Enter the no:";

               cin>>n;


              while(n!=0)

            {

            remainder=n%10;

           reverse_no= reverse_no*10+remainder;

          n=n/10;

          }

          cout<<"Reverse Number is:"<<reverse_no;

         return 0;

         }

*Logic of this code:

We use while loop for this code. the while loop execute when the condition is true.

here inside while loop i write the logic.

suppose consider the number(n=1234)

The user give the input n=1234.

inside the while loop first cheack the condition is true or false.(1234!=0) which  is true.

then it is going to remainder where remainder= n%10 (1234%10 == 4)

After that reverse_no= reverse_no*10+remainder(initially reverse_no=0)

(reverse_no= 0+4).

therfore reverse_no =4;

n=n/10;   (1234/10==123).

After that the number(n) will be 123. after that while loop is executed.

remainder= 123%10 == 3;

reverse_no = 4*10+3 == 43;

n= 123/10 == 12;

After that the number(n) will be 12. after that while loop is executed.

remainder= 12%10 == 2;

reverse_no = 43*10+2 == 432;

n= 12/10 == 1;

After that the number(n) will be 1. after that while loop is executed.

remainder= 1%10 == 1;

reverse_no = 432*10+2 == 4321;

n= 1/10 == 0;

and now here the while loop breaks because (n==0).

                                                                                             - Saurabh Shitole.


Comments

Popular posts from this blog