Home > other >  Counting the number of zero in an integer
Counting the number of zero in an integer

Time:10-14

The program would ask the user an integer input. and it counts how many zero the int has. constraints: use while loop

ex: input: 2400 count: 2

now I have no problem in that part, only when the user would input a zero. supposed it counts 1.

ex: input 0 count: 1

but then the program returns count 0.

here's the code:

int main(){
    int n, counter = 0;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    
    while(n != 0){
        if(n % 10 == 0){
            counter   ;
            n=n/10;
        }else{
            break;
        }
    }
      
      printf("%d", counter);
    
    return 0;
}

CodePudding user response:

You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0

Here is what I would have done :

 int main()
{
    int num, count = 0;
    
    scanf("%d",&num);
    
    
    if (num == 0) {
        printf("1");
        return 0;
    }
    
    
    while(num > 0) //do till num greater than  0
    {
        
        int mod = num % 10;  //split last digit from number
        num = num / 10;    //divide num by 10. num /= 10 also a valid one 
        if(mod == 0) count   ;
    
    
    }
     printf("%d\n",count);
    return 0;
}

Just don't forget to consider everything that can happen with a condition that you set

**Fixed it

CodePudding user response:

  1. Use functions.
int countZeroes(int x)
{
    int result = !x;   // if x == 0 then result = 1

    while(x)
    {
        result  = !(x % 10);
        x /= 10;
    }
    return result;
}
int main(void)
{
    printf("%d\n", countZeroes(0));
    printf("%d\n", countZeroes(1000));
    printf("%d\n", countZeroes(-202020));
}

https://godbolt.org/z/91hKr46eo

CodePudding user response:

As earlier mentioned, the problem is with the loop:

while(n != 0){
        if(n % 10 == 0){
            counter   ;
            n=n/10;
        }else{
            break;
        }
    }

It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too. You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way. Just do as follows:

do{
        if(n % 10 == 0){
            counter   ;
            n=n/10;
        }else{
            break;
        }
} while( n != 0 );

This should work(if i didnt mess up the braces/semicolumns).

  • Related