Program to Count the Number of Digits

In this example, you will learn to count the number of digits in an integer entered by the user. For example if we input 1234 then program returns 4.

C Program to Count the Number of Digits Using Loop

	
#include <stdio.h>
int main() {
    long long n;
    int count = 0;
    printf("Enter an positive number: ");
    scanf("%lld", &n);
    
    //this loop runs till value of n not equal to 0
    while (n != 0) {
        n /= 10;     // n = n/10
        ++count;
    }

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

Output :

	
Enter an positive number: 12563
Number of digits: 5
	

C Program to Count the Number of Digits Using User Define Function

	
#include <stdio.h>

int countDigit(long long n)
{
    int count = 0;
    while (n != 0)
    {
        n = n / 10;
        ++count;
    }
    return count;
}
int main(void)
{
    long long n;
    printf("Enter an positive number: ");
    scanf("%lld", &n);
    printf("Number of digits : %d", countDigit(n));
    return 0;
}
	

Output :

	
Enter an positive number: 12586947
Number of digits : 8
	

Share your thoughts

Ask anything about this examples