Related Articles

# C Program to count the number of zeros from 0 to N

• Difficulty Level : Hard
• Last Updated : 07 Aug, 2020

Given a number N, the task is to write C program to count the number of zeros from 0 to N.

Examples:

Input: N = 10
Output: 2
Explanation:
The number with zeros are 0, 10 till 10. Hence the count of zeros is 2.

Input: N = 20
Output: 3
Explanation:
The number with zeros are 0, 10, 20 till 20. Hence the count of zeros is 3.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

1. Iterate from 0 to N.
2. For each number do the following:
• Store the above number in a variable temp.
• For each digit in temp, if the digit is zero then increment the zero count by 1.
3. Print the count of zeros calculated in the above steps.

Below is the implementation of the above approach:

 `// C program for the above approach``#include `` ` `// Function to count zero in temp``int` `countZero(``int` `temp)``{``    ``int` `cnt = 0;`` ` `    ``// Iterate each digit in temp``    ``while` `(temp) {`` ` `        ``// If digit is zero, increment``        ``// the count``        ``if` `(temp % 10 == 0)``            ``cnt++;`` ` `        ``temp /= 10;``    ``}`` ` `    ``// Return the final count``    ``return` `cnt;``}`` ` `// Function that counts the number of``// zeros from 0 to N``void` `countZerostillN(``int` `N)``{``   ``// To store the finalCount of zero``    ``int` `finalCount = 1;`` ` `    ``// Iterate from 0 to N``    ``for` `(``int` `i = 1; i <= N; i++) {`` ` `        ``// Function call to count the``        ``// zeros in variable i``        ``finalCount += countZero(i);``    ``}`` ` `    ``// Print the final Count of zero``    ``printf``(``"%d"``, finalCount);``}`` ` `// Driver Code``int` `main()``{``    ``// Given number``    ``int` `N = 20;`` ` `    ``// Function Call``    ``countZerostillN(N);``}`
Output:
```3
```

Time Complexity: O(N)
Auxiliary Space: O(1)

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.

My Personal Notes arrow_drop_up