A C program to count set bits in an integer

We can write solution for this problem in two way i.e.

  1. Using non-recursive method
  2. Using recursive method.

Here is the C program to count set bits in an integer with the help of bit-wise operator using non-recursive method.

/* 1. Non-recursive : C program to Count set bits in an integer */
#include<stdio.h>
/*
* numOfSetBits() : to get number of set bits of
* positive integer n using bit-wise operator
*/
int numOfSetBits ( unsigned int num )
{
int numSetBits = 0;
while ( num )
{
numSetBits += num & 1;
num >>= 1;
}
return numSetBits;
}
int main()
{
int n = 14, result = 0;
result = numOfSetBits( n );
printf ( "The number of set bits are %d\n", result );
return 0;
}

Here is the C program to count set bits in an integer with the help of bit-wise operator using recursive method.

/* 2. Recursive : C program to Count set bits in an integer */
#include<stdio.h>
/*
* numOfSetBits() : to get number of set bits of
* positive integer n using bit-wise operator
*/
int numOfSetBits ( int num )
{
if ( num == 0)
return 0;
  else
/* if last bit set add 1 else add 0 */
return (num & 1) + numOfSetBits ( num >> 1);
}
int main()
{
int n = 14, result = 0;
result = numOfSetBits( n );
printf ( "The number of set bits are %d\n", result );
return 0;
}

To contribute :

” If you like Advance Computing and would like to contribute, you can  mail your article to “computingadvance@gmail.com”. You will get credit as your name , email id, designation with article on this blog. “

Leave a Reply