In this article, we will write a C program to count the number of digits in an integer.
The program prompts the user to enter an integer, counts the total number of digits in that integer and prints the total count on the screen.
Sample Input:
Enter an integer: 92134
Sample Output:
Number of digits: 5
Here is the C program that counts the total number of digits in an integer:
// C program to count the total // number of digits in an integer #include <stdio.h> #include<time.h> int main(){ int num, count = 0; printf("Enter an integer: "); scanf("%d", &num); // Runs until num becomes zero do{ num = num / 10; count ++; } while(num!=0); printf("Number of digits: %d", count); return 0; }
Output:
Enter an integer: 92134 Number of digits: 5
Code Explanation:
- The program first declares two integer variables,
num
andcount
and initialize thecount
to zero. - The user is prompted to enter an integer using the “printf()” and “scanf()” functions.
- The do-while loop runs until the “num” variable becomes zero.
- Inside the do-while loop, the “num” variable is divided by 10 to remove the last digit of the entered integer.
- The “count” variable is incremented each time the loop runs to keep track of the number of digits.
- Once the loop finishes running, the final value of “count” is printed to the console using the “printf()” function.
That’s all for this article. Thanks for reading!