assignment-p-08.c (807B)
1 /* Write a C program that includes a user-defined function named countSetBits with the 2 signature int countSetBits(int num);. The function should count and return the number of 3 set bits (1s) in the binary representation of the given number. */ 4 5 #include <stdio.h> 6 7 int countSetBits(int); 8 9 int main() 10 { 11 int num, result; 12 printf("Enter the number: "); 13 scanf("%d", &num); 14 if (result = countSetBits(num)) 15 { 16 printf("\nNumber of set bits in %d: %d", num, result); 17 } 18 else 19 { 20 printf("\nThere is no set bits in %d", num); 21 } 22 return 0; 23 } 24 25 int countSetBits(int num) 26 { 27 int count = 0; 28 int mask= 1; 29 int i = 1; 30 while (i <= 16) 31 { 32 if (num & mask) 33 { 34 count++; 35 } 36 mask <<= 1; 37 i++; 38 } 39 return count; 40 }