Write c program ,Given unsigned positive integers count number of 1s. for example if the given number is 11, its binary equivalent isĀ 00001011, hence the outputĀ  would be 3.

Given unsigned positive integers count number of 1s

#include<stdio.h>

int count(unsigned int num)
{
  int cnt = 0;
  // try to convert num into binary
  while(num)
  {
    // count 1
    if(num%2)
     cnt++;
    num = num/2;
  }
  return cnt;
}
int main()
{
  unsigned int a=0;
  printf("Entter a positive decimal number:");
  scanf("%d",&a);
  int cnt = count(a);
  printf("%d\n",cnt);
  return 0;
}

 



Related Contents to follow