QWERTY
QWERTY

Reputation: 2315

Recursive search through an integer

I was having some problem when trying to do a recursive in C programming. Here is the expected output:

Enter a number: 1234567
Enter the digit position: 3
rDigitValue1(): 5
rDigitvalue2(): 5 

And here is my code:

int rdigitValue1(int num, int k)
{
    int count = 0, output;
    if (count != k) {
        rdigitValue1(num / 10, k);
        count++;
    }
    else {
        output = (num % 10);
    }
    return output;
}

The parameter num is the number whereas the parameter k is the position. With these code, when I try to run the program, it just crashed without prompting any error message. Any idea?

Modified

void rdigitValue2(int num, int k, int *result)
{
    if (k != 1) {
        rdigitValue2(num / 10, k - 1, result);
        *result = num;
    }
    else {
        *result = num % 10;
    }
}

Upvotes: 0

Views: 91

Answers (3)

Kenil Domadia
Kenil Domadia

Reputation: 63

Expected output :

    rDigitvalue2(): 5 

Current output :

    rDigitvalue2(): 1234567

The function you wrote is :

void rdigitValue2(int num, int k, int *result)
{
if (k != 1) {
    rdigitValue2(num / 10, k - 1, result);
    *result = num;
}
else {
    *result = num % 10;
}
}

The above function works well in my g++ compiler. The value for *result in the end is 1234567 for your function because your recursive call ends in the line *result = num. You need to remove this line and modify your function to :

void rdigitValue2(int num, int k, int *result)
{
if (k != 1) {
    rdigitValue2(num / 10, k - 1, result);
}
else {
    *result = num % 10;
}
}

Output : rDigitvalue2(): 5

Upvotes: 0

mvd
mvd

Reputation: 2720

You are getting a stack overflow! You are never decrementing digit position and keep looping. Your current code can be simplified to:

int rdigitValue1(int num, int k)
{
    if (k != 0) {
        rdigitValue1(num / 10, k);
    }
}

Upvotes: 2

Paul
Paul

Reputation: 141839

You should use k - 1 for your recursive call, you keep testing if k == 0 and of course it never is since you keep using the same value for k. You also need to store the value returned from the recursive call so that you can return it:

output = rdigitValue1(num / 10, k - 1);

Upvotes: 1

Related Questions