C Program to Count the Number of Trailing Zeroes in Integer

«
»

This is a C Program to count the number of trailing zeroes in integer.

Problem Description

This C Program counts the number of trailing zeroes in integer.

Problem Solution

Take input from the user and counts the number of trailing zeroes in given integer as shown in the program below.

advertisement
Program/Source Code

Here is source code of the C Program to count the number of trailing zeroes in integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Count the Number of Trailing Zeroes in Integer
 */
#include <stdio.h>
 
void main()
{
    int j = 31, i, count = 0;
    unsigned int num;
    int b[32] = {0};
 
    printf("enter the number:");
    scanf("%d", &num);
    while (num != 0)
    {
        if (num & 1 == 1)
        {
            break;
        }
        else
        {
            count++;
            num = num >> 1;
 
        }
    }
    printf("\n%d", count);
}
Program Explanation

This C Program we are reading the number using ‘num’ variable. While condition statement is used to check that the number is not equal to 0. If the condition is true then execute the statement.

advertisement

If else condition statement is used to check that the copy of the bit 1 in the value of ‘num’ variable is equal to the value of 1. If the condition is true, then exit the condition statement using break statement.

Otherwise, if the condition is false then execute the else statement by increment the value of ‘count’ variable. Using binary right shift operator the value 1 is moved right by the number of bits specified by the value of ‘num’ variable and assign to ‘num’ variable. Print the number of trailing zero’s in integer.

Runtime Test Cases
 
$ cc bit4.c
$ ./a.out
enter the number:128
7
$ ./a.out
enter the number:-127
0

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn