Getting the position of a digit in a number using recursion

I am currently writing code that returns the position of a specific digit of user input. I am currently facing a problem when my pointer is not working, which I believe is related 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
}
+4
source share
4 answers

Effectively return 1 base position in which your rDigitPos2will look 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
    }
}

Since your first part of the recursion will find the position from the last, you will need to find the length of the number, then it length-position from lastwill be your answer.

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

to

rDigitPos2(num/10, digit, pos);

paramater (pos) , (& pos) (pos).

  • ,
  • , . ( 0, 1)
  • () , .

-Happy :)

+1

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

rDigitPos2(num/10, digit, pos);

0

GCC , &pos 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);
                              ^~~~

, , :)

0

Source: https://habr.com/ru/post/1608193/


All Articles