⑪ C Program to Count Digits in a Number (With Program and Explanation)

 

๐Ÿ”ข C Program to Count Digits in a Number

๐Ÿ“Œ Problem Statement

Write a C program to count the total number of digits in a given integer number.


๐Ÿง  Understanding the Logic

To count digits in a number:

  1. Take a number as input.

  2. Repeatedly divide the number by 10.

  3. Each division removes the last digit.

  4. Count how many times the division happens until the number becomes 0.

๐Ÿ‘‰ Each division means one digit.


✨ Special Case

  • If the number is 0, the digit count is 1.


๐Ÿงพ Algorithm (Step by Step)

  1. Start

  2. Read the number n

  3. If n == 0, set count = 1

  4. Else

    • While n > 0

      • count++

      • n = n / 10

  5. Print count

  6. End


๐Ÿ’ป C Program to Count Digits

#include <stdio.h> int main() { int num, count = 0; printf("Enter a number: "); scanf("%d", &num); // Special case when number is 0 if (num == 0) { count = 1; } else { while (num != 0) { count++; num = num / 10; } } printf("Total number of digits = %d", count); return 0; }

๐Ÿ“ค Sample Output Examples

▶ Example 1

Input

Enter a number: 12345

Output

Total number of digits = 5

๐Ÿ“š Explanation of Code

  • num / 10 removes the last digit

    • Example: 123 / 10 = 12

  • Loop runs until num becomes 0

  • Each loop increases count by 1

  • Final count is the number of digits


✅Conclusion

In this program, we learned how to Count Digits in a Number.


๐Ÿ“˜ C Programming Series – What’s Next?

๐Ÿ‘‰ In the next post of this series, we will learn how to Swap Two Numbers (Without Temp) with complete explanation and output examples. Stay tuned! ๐Ÿš€


Comments

Popular posts from this blog

⓮C Program to calculate Simple Interest (With Program and Explanation)

⑫ C Program to Swap Two Numbers Without Using a Temporary Variable (With Program and Explanation)

9️⃣C Program to Find LCM of Two Numbers (With Program and Explanation)