C program to count trailing zeros in a binary number

Write a C program to input any number from user and count number of trailing zeros in the given number using bitwise operator. How to find total number of trailing zeros in any given number using bitwise operator in C programming.

Example

Input

Input any number: 22

Output

Trailing zeros: 1

Required knowledge

Basic C programming, Bitwise operator, If else, Loop

Logic to count trailing zeros in a binary number

Counting trailing zeros in a binary number is an easy task if you know how to find first set bit in a binary number. As total number of trailing zeros is equal to the order of the first set bit.
Trailing zeros in binary number

Program to count trailing zeros in a binary number

/**
 * C program to count trailing zeros in a binary number using bitwise operator
 */

#include <stdio.h>
#define INT_SIZE sizeof(int) * 8

int main()
{
    int num, count=0, i;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    // Iterate over each bit of the number
    for(i=0; i<INT_SIZE; i++)
    {
        //If a set bit is found
        if((num >> i ) & 1)
        {
            //No need to run further
            break;
        }

        count++;
    }

    printf("Total number of trailing zeros in %d is %d.", num, count);

    return 0;
}

You can also short the above program using while loop.

Program to count trailing zeros in a binary number using while loop

/**
 * C program to count trailing zeros in a binary number using bitwise operator
 */

#include <stdio.h>

int main()
{
    int num, count=0;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    while(!(num & 1))
    {
        count++;
        num >>= 1;
    }

    printf("Total number of trailing zeros = %d.", count);

    return 0;
}

Output

Enter any number: 48
Total number of trailing zeros in 48 is 4.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>