C program to count number of digits in a number




Code 1:
Count the number of digits in c programming language

#include<stdio.h>
int main(){
  int num,count=0;

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

  while(num){
      num=num/10;
      count++;
  }
  printf("Total digits is:  %d",count);
  return 0;
}

Sample output:
Enter a number: 23
Total digits is:  2

Code 2:
C code to count the total number of digit using for loop

#include<stdio.h>
int main(){
  int num,count=0;

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

  for(;num!=0;num=num/10)
      count++;

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

  return 0;
}

Sample output:
Enter a number: 456
Total digits is:  3

Code 3:
Count the digits of a given number in c language using recursion

#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;
}

Sample output:
Enter a number: 1234567
Total digits is:  7





Post a Comment