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 any number: 22
Output trailing zeros: 1

Required knowledge:

Basic C programming, Bitwise operator, If else, Loop

Logic:

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 a binary number

Program:

/**
 * 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;

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


Program: Another approach

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

#include <stdio.h>

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

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


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment