Q. C Program to Count the Number of Digits in a Number.


Here you will find an algorithm and program in C programming language to count number of digits in a number. First let us understand this.

Explanation : Suppose an input number is given as 12341 then the output will be 5 as there are 5 digits in the given number and digits are 1, 2, 3, 4, 1.

Algorithm to count the number of digits in a given number


START
step 1 : Declare/Read a number and store it in some variable say num.
step 2 : Initialize another variable to store total digits say count = 0.
step 3 : If num != 0 then increment count by 1 i.e. count++.
step 4 : Divide num by 10 to remove last digit of the given number i.e. num = num / 10.
step 5 : Repeat step 3 to 4 till num > 0 or num != 0.
STOP

C Program to Count Number of Digits in a Number

#include <stdio.h>
int count_digit(long long num) 
{ 
	int count = 0; 
	while (num != 0) { 
		num = num / 10; 
		++count; 
	} 
	return count; 
}
 
int main(void) 
{ 
	long long num = 874512369; 
	printf("Number of digits : %d", count_digit(num)); 
	return 0; 
} 

Output

Number of digits : 9