Recursion on Reversing Digits with pointers

Feb 24, 2012 at 4:59pm
Hi guys,

Currently i am working on reversing the digits using recursion.

I have done up the code for recursion but i don't understand why i always get the output of 0.

Could u guys care to enlighten?

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdio.h>

void reverseDigits(int n, int *result);

main(void)
{
int result;
int n;
int cont = 1;
while (cont) {
result = 0;
printf("Enter a number: ");
scanf("%d", &n);
reverseDigits(n, &result);
printf("result = %d\n", result);
printf("Continue (1 for yes, 0 for no): ");
scanf("%d", &cont);
}
return 0;
}


void reverseDigits(int n, int *result){


if(n>0){
return;
}
int reverseNum=reverseNum*10+(n%10);
n=n/10;
*result=reverseNum;
int x=*result;
reverseDigits(n,&x);
}
Feb 24, 2012 at 5:07pm
lines 27-29:

if (n>0) return;

Is that really your intent? You are effectively saying that for any number greater than 0, you will not process it. I expect that you have your >< signs mixed up.
Feb 24, 2012 at 5:21pm
Also I don't see where you initialize reverseNum in line 30. I think you are using garbage stuff here.

What reverseNum is supposed to be? The number you keep in every recursion like in n=123, in 1st recursion being 1 etc?
Feb 24, 2012 at 5:23pm
even if it is switched to < , the program still doesn't run correctly. compilation has no error but when it runs it says that it has stopped working. any idea what went wrong?
Last edited on Feb 24, 2012 at 5:26pm
Feb 24, 2012 at 5:35pm
reverseNum is supposed to store the digit from the back for each recursion.

lets says n=1234
reverseNum will store 4 at first den 3 at second and so on and so forth.

den the value of n will be used to called reverseDigit function again and the value of reverseNum should b stored inside the pointer result.
Topic archived. No new replies allowed.