JWH_
JWH_

Reputation: 267

Getting the position of a digit in a number using recursion

I am current writing a code which returns the position of a certain digit of a user input. I am currently facing a problem where my pointer is not working, which I believe is due to the recursion function. Any advice would be appreciated!

#include <stdio.h>

void rDigitPos2(int num, int digit, int *pos);

int main()
{
    int number;
    int digit, result = 0;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("Enter the digit: ");
    scanf("%d", &digit);
    rDigitPos2(number, digit, &result);
    printf("rDigitPos2(): %d", result);
    return 0;
}

void rDigitPos2(int num, int digit, int *pos) {
    static int count = 0;
    if (num % 10 != digit) { 
    count++; //increment of position
    rDigitPos2(num/10, digit, &pos);

    *pos = count;//returns the position of the digit
}

Upvotes: 4

Views: 1415

Answers (4)

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

Effectively return the 1 base position your rDigitPos2 would be like

void rDigitPos2(int num, int digit, int *pos)
{
    static int count = 0;
    if (num % 10 != digit)
    {
        count++; //increment of position
        rDigitPos2(num/10, digit, pos);   //Not &pos

    }
    else
    {
        *pos = count;     //Current position from the last
        while(num!=0)
        {
            num = num/10;
            count++;
        }
        *pos = count-*pos;  //Original position form beginning
    }
}

As your first part of recursion find the position from the last, it would be need to find the length of the number then length-position from last would be your answer.

Upvotes: 0

shashank
shashank

Reputation: 31

rDigitPos2(num/10, digit, &pos);

to

rDigitPos2(num/10, digit, pos);

Since the paramater (pos) is already passed to the function in the first call, passing the (&pos) in the recursive call will lead to passing of the address of address of (pos).

Some improvements

  • You will also need to handle properly the case when the input digit does not appear in the number
  • You are providing the position from last digit and not from the start. (Also your count starts from 0 and not 1)
  • It is redundant to include the (digit) parameter in the function call, as it is a constant.

-Happy coding :)

Upvotes: 1

Nitin Tripathi
Nitin Tripathi

Reputation: 1254

GCC compiler gives a significant warning, replace &pos with pos

ss.c:20:31: warning: incompatible pointer types passing 'int **' to parameter of type 'int *'; remove & [-Wincompatible-pointer-types]
    rDigitPos2(num/10, digit, &pos);
                              ^~~~

Humble request, Please do not ignore warnings :)

Upvotes: 0

asio_guy
asio_guy

Reputation: 3767

change

rDigitPos2(num/10, digit, &pos);

to

rDigitPos2(num/10, digit, pos);

along with minor details

Upvotes: 0

Related Questions