Count Trailing Zeros in Integer C Program

By | June 6, 2016

C Program To Count Trailing Zeros in Integer

Learn How to write a C Program to Count Trailing Zeros in Integer using For Loop and While Loop. The C Code to Count the Trailing Zeros in a Number makes use of Modulus (%) and Division (/) operators to fetch the Last Digit of a given Number.

Normally, the program Converts the Decimal Number into Binary and then calculates the Trailing Zeros. But, we have manipulated the program to calculate trailing zeros in a given number without binary conversion.

Example of Trailing Zeros in an Integer

23000

Count of Trailing Zeros = 3

Also Read: C Program To Calculate Distance Between Two Points

Method 1: C Program To Count Trailing Zeros in a Number using While Loop

#include<stdio.h>

int main()
{
      int num, temp, count = 0;
      printf("\nEnter a Number:\t");
      scanf("%d", &num);
      temp = num;
      while(num >= 0)
      {
            if(num%10 == 0)
            {
                  count++;
                  num = num / 10;
            }
            else
            { 
                  break;
            }
      }       
      printf("\nNumber of Trailing Zeros in %d = %d\n", temp, count);
      return 0;
}

Also Read: C Program To Implement FCFS Algorithm

 

Method 2: Count Number of Trailing Zeros in an Integer in C Programming using For Loop

#include<stdio.h>

int main()
{
      int num, temp, count = 0;
      printf("\nEnter a Number:\t");
      scanf("%d", &num);
      for(temp = num; num >= 0; count++)
      {
            if(num%10 == 0)
            {
                  num = num/10;
            }
            else
            { 
                  break;
            }
      }      
      printf("\nNumber of Trailing Zeros in %d = %d\n", temp, count);
      return 0;
}

Also Read: C Program To Find Arithmetic Progression

 

Output

C Program To Count Trailing Zeros in Integer

If you have any compilation errors or doubts in this C program to Count Trailing Zeros in Integer, let us know about in the Comment Section below.

Let's Discuss