C-Program to count the number of ones in a Number


We will see the different ways in which a number of ones in a number can be calculated. For example in the number 25(11001) it has 3 ones present in it. We will get that value programmatically.


There are two methods for getting the result:

Method1:


#include <stdio.h>
#include <string.h>

main()
{
  int number,count=0;
  
  printf("Enter the number\n");
  scanf("%d",&number);
  
  while(number>0){
      count++;
      number=number&(number-1); //this will clear the last set bit
      
  }
  printf("The count is %d",count);
}



Method 2:

#include <stdio.h>
#include <string.h>

main()
{
  int number,count=0;
  
  printf("Enter the number\n");
  scanf("%d",&number);
  
  while(number>0){ //checking the last bit whether it is 1 and shifting by 1
      if(number&1)
        count++;
      number=number>>1;
  }
  printf("The count is %d",count);
}



Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto