C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Sunday, February 16, 2014

Convert a Number into Reverse Number Program in C Plus Plus

C++ Reverse Number Conversion Program Logic

Reverse Number Program logic in C Plus Plus using While Loop
Reverse Number Program in C Plus Plus using While Loop

Q: Write a C++ Program to input an integer number and display its Reverse Number. For example if the input is the number 123, the Reverse Number will be 321.

Reverse Number Logic in common programming is very important. Although, it is difficult for beginner programmers, you must learn and understand REVERSE NUMBER Program in C++ or JAVA. This will be helpful for further improvements in your programming logic.

Reverse the input number program in C++
Reverse the input number program in C++
  • First of all we suppose that the number entered is 123.
  •  Let the given number num = 123
  • Copy the number in temporary variable temp so that temp = 123

First Iteration of While Loop

  • We start a while loop with condition temp>0. Since temp=123 so loop will start for first time.
  • Now we will divide number 123 by 10 so that the remainder R = 3 and Quotient Q = 12
  • Put the values in statement rev = rev * 10 + R
  • rev = 0 * 10 + 3
  • rev = 3
  • Assign the value of Quotient Q to temp so that temp = 12 now.
  • Since temp 12 is >0, so the while loop will execute again.
  •  

Second Iteration of While Loop

  • Now we will divide number temp 12 by 10 so that the remainder R = 2 and Quotient Q = 1
  • Put the values in statement rev = rev * 10 + R
  • rev = 3 * 10 + 2
  • rev = 30+2
  • rev = 32
  • Assign the value of Quotient Q to temp so that temp = 1 now.
  • Since temp 1 is >0, so the while loop will execute again.

 Third Iteration of While Loop

  •  Now we will divide number temp 1 by 10 so that the remainder R = 1 and Quotient Q = 0
  • Put the values in statement rev = rev * 10 + R
  • rev = 32 * 10 + 1
  • rev = 320+1
  • rev = 321
  • Assign the value of Quotient Q to temp so that temp = 0 now.
  • Since temp 0 is not >0, so the condition temp>0 will evaluate to false so that the while loop will terminate.
While loop reverse a number program C++
While loop reverse a number program

Conclusion

       So the Required Reverse Number is 321.


The Actual C++ Code of Reverse Number Program


/*
Program to input a number, then display its Reverse number.
(c) Www.EasyCppProgramming.Blogspot.Com
*/


#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
     int num, temp, rev=0, R, Q;

     clrscr();

     cout<<"Enter a number to reverse=";

     cin>>num;

     temp = num;

     while ( temp>0 )

     {

       Q = temp/10;
       R = temp % 10;
       rev = rev*10 + R;

       temp = Q;

     }

     cout<<"\n The Reverse Number = "<<rev;
     getch();

     }
Share:

1 comment:

We Love To Hear From You!

EasyCPPprogramming.blogspotcom

Labels