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