# Thread: Finding digits in a number

1. ## Finding digits in a number

I supposed to write a recursive code that finds the position of a particular digit in a number, starting from the right. Eg position(12345,3) = 3, position(123513, 3) = 1 ...

My code goes like this
Code:
```int position(int number, int digit) {
if  ((number%10) == digit) return 1;
return 1+ position(number/10, digit);
}```
This works well and fine for all numbers except for cases when the digit is not found in the number. Eg position(12345, 8)
I am supposed to return a 0 value, not print nothing when I use printf to print out the value.
Eg position(1000, 4) = 0

It looks easy but I am stumped by it. I'm sure some of you experts out there can help me with this.
Thanks.

2. This is not the best way to do it, but it works.
Code:
```int search(int num, int sf)
{
char temp[100];
sprintf(temp, "%d", num);
char *pos = strrchr(temp, sf + '0');
if (pos)
return temp + strlen(temp) - pos;

return 0;
}```
To search from left to right, just change strrchr to strchr.

3. I was looking for a recursive solution along the lines of my solution.... I'm sure it can be done... it's just that I don't know how

Pier.

4. This is also not recursive, but works fine.
Code:
```int position(int number, int digit)
{
int pos = 0;
do
{
pos++;
if ((number%10) == digit)
return pos;
}
while (number/=10);
return 0;
}```

5. Here a recursive function:

Code:
```int position(int number, int digit) {
int ret = 0;
if(number == 0) return 0;
if((number%10) == digit) return 1;
ret = position(number/10, digit);
return (ret==0 ? 0 : 1+ret);
}```

6. Cool, Monster.... thanks a lot.

Pier.
Originally posted by Monster
Here a recursive function:

Code:
```int position(int number, int digit) {
int ret = 0;
if(number == 0) return 0;
if((number%10) == digit) return 1;
ret = position(number/10, digit);
return (ret==0 ? 0 : 1+ret);
}```