C Program to Count Number of Digits in an Integer

CodingTute

C Program to Count Number of Digits in an Integer

In this example, you will learn to count the number of digits present in the given integer.

C Program to Count Number of Digits in an Integer

#include <stdio.h>
int main() {
  long n;
  int count = 0;
  printf("Enter an integer: ");
  scanf("%ld", &n);
 
  while(n!=0){
      n/=10;   //will remove the last digit
      count++;
  }

  printf("Number of digits: %d", count);
}

Output

Enter an integer: 1233
Number of digits: 4

Explanation

Firstly, we will read the integer from the user and store it in a variable n and initialize a variable count with 0.

Now, we will remove the last digit of the given number stored in n and increment the count.

The last digit of a number can be removed by dividing the number with 10 (n=n/10).

We need to increment the count until n becomes 0. So we will iterate the while loop till n!=0.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.