In this tutorial, you will learn how to write a C program to count number of digits in an integer. For example number 3456 has 4 digits, number 555 has 3 digits etc.
Program to count number of digits in an integer
The logic used in this program is pretty simple. The user input is captured and stored in a variable number
. We then copied the value of number to another temporary variable temp
. This is because, we need to perform some arithmetic operations on the temp
.
In the next step, inside do-while loop we are dividing the number by 10 and storing the quotient value into the number itself (temp /=10 is same as temp = temp/10). The purpose of doing this is to remove the last digit from the number
and count the removed digit by increasing the counter count
by 1.
The loop keeps repeating until all the digits are removed and the number (temp
) becomes zero, at this point the the count
variable has counted the number of digits in the number.
#include <stdio.h>
int main() {
long number, temp;
int count = 0;
printf("Enter an integer: ");
scanf("%ld", &number);
//copying the number in a temporary variable to perform
//calculations on it.
temp = number;
//Here we are counting the digits of the input
//number. At every loop iteration, we are increasing
//the counter by 1 and removing the last digit from the
//number by dividing it by 10. This goes on until number
//becomes 0.
do {
temp /= 10;
++count;
} while (temp != 0);
printf("Number of digits in the number %ld is: %d", number,count);
}
Output: