Counting the number of digits with a recursion algorithm in c 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&lt;stdio.h&gt;

int countDigits(int n);

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

int countDigits(int n){
  if(n&gt;=0&amp;&amp;n&lt;10){
    return 1;
  }
  else{
    return 1+countDigits(n/10);
  }
}
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&gt;9; i/=10)
  {
    digits++;
  }
  return digits;
}

int countDigits(int n){
  if(n&lt;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.