C Program: Counting digits in an integer using Do-While Loop
10. Count Digits in a Number
Write a C program that implements a program to count the number of digits in a given integer using a do-while loop.
Sample Solution:
C Code:
Sample Output:
Input an integer: 12345 Number of digits: 5
Input an integer: -789 Number of digits: 3
Input an integer: 000 Number of digits: 1
Explanation:
Here are key parts of the above code step by step:
- int num;: Declares a variable to store the input number.
- int digitCount = 0;: Initializes a variable to store the count of digits.
- printf("Enter an integer: ");: Prompts the user to input an integer.
- scanf("%d", &num);: Reads the entered integer from the user.
- (num < 0) ? -num : num;: Takes the absolute value of the entered number.
- if (num == 0) { digitCount = 1; }: Handles the special case when the entered number is 0.
- do { ... } while (num != 0);: Uses a do-while loop to count the number of digits.
- digitCount++;: Increments the digit count for each digit encountered.
- num /= 10;: Removes the last digit from the number.
- printf("Number of digits: %d\n", digitCount);: Prints the count of digits.
- return 0;: Indicates successful program execution.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C program to count the number of digits in a number and determine whether the number is an Armstrong number.
- Write a C program to count the number of digits in a number and calculate the sum of those digits.
- Write a C program to count the number of digits and print each digit separately in reverse order.
- Write a C program to count the number of digits in a number and check if all digits are unique.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Calculate sum of Prime numbers with Do-While Loop.
Next: Calculating compound interest with User input Loop.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.