Count the Number of Digits in an Integer in C


Write a C Program to count the number of digits in an integer.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    long long num;
    int count = 0;
    printf("Enter an integer: ");
    scanf("%lld", &num);

    // Remove last digit from num in each iteration
    // Increase count by 1 in each iteration
    // Iterate until num becomes 0
    while (num != 0) {
        // num = num/10
        num /= 10;
    printf("Number of digits: %d", count);
Click Here to View the Output!
Enter an integer: 876543909
Number of digits: 9
Click Here to View the Explanation!
  • This program is used to count the number of digits in a number using a while loop.
  • In main(), a long long type variable num and an int type variable count is initialized.
  • The program requests the user to enter an integer and stores it in an integer variable num using the scanf() function.
  • A while loop with the condition (num != 0) is used which will continue iteration until num becomes equal to 0.
  • In each iteration, the last digit of num is removed, and the value of the variable count is incremented by 1.
  • Once all the digits of num are removed, the while condition will become false and the loop exits.
  • The final value of count will be printed which will be the number of digits of num.
%d bloggers like this: