Dodos
Dodos

Reputation: 49

Recursive function in C that returns the nth digit from the right of a given number

The function int digit(int number,int position) has to be recursive and return the digit of "number" in the position "position" from the right. So in my code where number=5864 and position=3 the function should return "8". Here's the main code.

#include <stdio.h>

int digit(int number,int position);

 int main (){
int number=5864, position=3, result;
result=digit(number,position);
printf("result: %d\n",result );
system("pause");

return 0;
}

int digit(int number,int position){}

I know that this question has already been asked but I'm really struggling to make it recursive. Thanks for your attention.

Upvotes: 0

Views: 1093

Answers (2)

Mureinik
Mureinik

Reputation: 311163

For a recursion definition, you need two things - a rule on how to move the recursion on, and a rule on how to stop the recursion. For this usecase, you can formalize these rules as follows:

  • If position == 1, return the rightmost digit
  • If position > 1, divide number by 10 and decrement position

Or, in C code:

int digit(int number, int position) {
    if (position == 1) {
        return number % 10;
    }
    return digit(number / 10, --position);
}

Note: This code is a bit simplistic, and doesn't handle invalid inputs. A non-positive position will send this code in to an endless recursion.

Upvotes: 1

Spinkoo
Spinkoo

Reputation: 2080

int digit(int number,int position){
        if(position==1) return number%10;
      return digit(number/10,--position);
   }

Upvotes: 0

Related Questions