bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / assignment-primary / assignment-p-08.c

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 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror