Question: I'm learning recursion and I think that I can finally wrap my head around it.

I had to write a program that given an integer would print out its number of digits and I wanted to know if it is correctly implemented and if there's anything I can do to make it better.

Here's my code:

```
#include<stdio.h>

int countDigits(int n);

int main(void){
  int n,result;
  printf("What is the number?\n");
  scanf("%d", &n);
  result=countDigits(n);
  printf("%d\n", result);
  return 0;
}

int countDigits(int n){
  if(n>=0&&n<10){
    return 1;
  }
  else{
    return 1+countDigits(n/10);
  }
}

```

Answer: 
I unfortunately cannot comment (not enough reputation), but in terms of performance and generated assembly code both variants are exactly same:

```
int countDigitsSane (int n){
  int digits=1;
  for(int i=n; i>9; i/=10)
  {
    digits++;
  }
  return digits;
}

int countDigits(int n){
  if(n<10){
    return 1;
  }
  else{
    return 1+countDigits(n/10);
  }
}

```

Pay attention, I have removed the redundant check in the recursive snippet.With that correction, the code generated by the compiler is almost 100% same, save for different choice of registers.

Having said that, it is indeed, better to avoid recursion in imperative languages (such as C++), however in functional languages (Haskell, OCaml etc.) , recursion is a normal thing, and the compiler guarantees it can optimise tail-recursive calls.
> 
> it is correctly implemented (?)
> 
> 
> 

No. Incorrect result when `n <= 10`.

Goal: Counting the number of digits with a recursion algorithm in c

Simply change the condition to handle all `int`.

```
int countDigits(int n){
  // if(n>=0&&n<10){
  if(n > -10 && n < 10) {
    return 1;
  }
  else {
    return 1 + countDigits(n/10);
  }
}

```