Open In App

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

Last Updated : 22 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

C




// 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);
}


Output:

3

Time Complexity: O(N*log10N) 

Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads