Hi A small correction Your code returns the first digit(not last digit) of the entered number.Here is the reason
You are calculating revNum after returning some value like this
return(rev(number/10)+revNum);
revNum=(number%10)*sum; sum=sum/10;
hence the second statement has no effect.
Also revNum is a local variable
So every time when you are calling a recursive function new local copies of sum(local variable) and revNum are getting created and initialized with 0 and 100 respectively.
Your recursive tree looks like this,For example 596 is the number passed to the recursive function.
rev(596) //call from main
rev(59)-->rev(5) // these are recursive calles
Now rev(5) returns 5(since 5 < 9) back to the caller i.e to rev(59) from there to the caller which is in main, resulting the display of the first digit, in this case it is 5.
How to fix it?
To fix that issue, you have to make them global variables(sum and revNum) also return statement should be at the end, after calculating the reverse number. Here is the simple code.
I made reverse variable as global to preserve the changes in it, finally I'm returning the same to the caller.
#include <stdio.h>
int reverse; //globally declared
int rev(int revNum)
{
if(revNum)
{
reverse = (reverse * 10) + (revNum % 10);
rev(revNum/10); //recursive call
}
else
return; //return back to caller when revNum becoms 0
return reverse;
}
int main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
printf("Reverse Number is:%d\n",rev(num));
return 0;
}
if(number<=9)elseif(number>0)what is that??There is something between 0-9 which is ready to satisfy both condition.revNum=(number%10)...will be never reachedsumis not preserved across recursion, among other things