Thursday, June 2, 2016

c program to count number of 1 in binary representation of a number

Problem Statement: count the no of ones in binary repesentation of a decimal number
#include<stdio.h>
#include<math.h>
void main()
{
 int i,k,l,j=0;
 printf("\nEnter a no");
 scanf("%d",&i);
 l=i;
//it will give the size of any data type in bits
 k=8*sizeof(int);
 while(k!=0)
  {
   if(i&1==1)
    {
     j++;
    }
   i=i>>1;
   k--;
  }
 printf("\nNo of one set in number is %d",j);
}

output
Enter a no10
No of one set in number is 2

No comments:

Post a Comment