C Program to count the number of zeros from 0 to N
Last Updated :
22 Feb, 2023
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:
- Iterate from 0 to N.
- 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.
- Print the count of zeros calculated in the above steps.
Below is the implementation of the above approach:
C
#include <stdio.h>
int countZero( int temp)
{
int cnt = 0;
while (temp) {
if (temp % 10 == 0)
cnt++;
temp /= 10;
}
return cnt;
}
void countZerostillN( int N)
{
int finalCount = 1;
for ( int i = 1; i <= N; i++) {
finalCount += countZero(i);
}
printf ("%d", finalCount);
}
int main()
{
int N = 20;
countZerostillN(N);
}
|
Time Complexity: O(N*log10N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...