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

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.

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program for the above approach
#include <stdio.h>
  
// 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);
}

chevron_right


Output:

3

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




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.