Sunday, January 22, 2012

Write a program to Count the digits of a given number without using loop

#include<stdio.h>

int countDigits(num);
int main(){
  int num,count;

  printf("Enter a number: ");
  scanf("%d",&num);

  count = countDigits(num);

  printf("Total digits is:  %d",count);
  return 0;
}

int countDigits(int num){
    static int count=0;

     if(num!=0){
          count++;
         countDigits(num/10);
    }

    return count;
}

1 comment:

  1. Cool! A rather simple one-liner would be ceil(log10(n)) :) That's it.

    ReplyDelete