function to reverse an integer – CSKC
Sign In

Search

Solved Problem #CPP#3086    siteicon   siteicon  

Problem Statement - function to reverse an integer

Write a program to reverse the given integer number.using a separately called function to reverse the number.

Solution

TC++ #3086

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

int revnum(int); //Prototype for reversing a number declared here

int n; cout<<“Enter a positive integer: “; cin>>n;
Collecting value from the user.

cout<<“Reversed number of “<<n<<” would be “<<numrev(n)<<endl;
revnum(n) directly called in the cout chain as it returns the reversed number directly.

int revnum(int n)
{
int rem,nr=0;
Related variables are declared, rem will contain the remainder of mod operations and nr has been used to maintain the reversed number.

int nc=n;
Since forthcoming loop of reversal of number will affect the original number so it is better to make a number copy in nc and then the loop is worked on the working copy.

while(nc>0) //This loop is to reverse the number, works till all digits are exhausted
{
rem=nc%10; 
Last digit is extracted here

nr=nr*10+rem;
last number is shifted left by multiplying it with 10 and then new last digit is added.

nc=nc/10;
Last digit of number is dropped so that operation can continue with other digits
}
return nr;
Finally we are left with reversed number in the nr variable, so this is returned to be used by the calling function.
}

Notes

  • Negative numbers can also be reversed by passing the absolute value to this function.

Common Errors

  • Student some time forget to retain the number copy in another variable and directly act on given input variable. In this case the original number value is lost after the loop is complete.


Share

Created: 27-Jan-2018 21:43 | Updated: 29-Nov-2018 17:20|