Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

Count Set Bits in an Integer (C Program)

Count Set Bits in C

πŸ”’ Count Set Bits in an Integer (C Program)

#include<stdio.h>
int count_set_bits(int num)
{
    unsigned int mask = (unsigned int)num;
    int count = 0;
    while(mask)
    {
        count += mask & 1;
        mask >>= 1;
    }
    return count; 
}
int main( )
{
    int number;
  //  printf("Enter the number: ");
    scanf("%d", &number);
    int result = count_set_bits(number);
    printf("The count of set bits is %d\\n", result);
}
  

πŸ“˜ Explanation:

This program counts the number of set bits (1s) in the binary representation of an integer using bitwise operations.

πŸ”Ή `mask & 1` checks the least significant bit (LSB) of the number.
πŸ”Ή If it's 1, `count` is incremented.
πŸ”Ή The mask is then right-shifted using `mask >>= 1` to check the next bit.
πŸ”Ή The loop continues until the entire binary number is processed.

πŸ”Έ Note: Casting `num` to `unsigned int` ensures correct behavior for negative numbers (avoiding sign extension).

πŸ” Sample Output:

Input:
13

Output:
The count of set bits is 3
    

🏷️ Keywords:

count set bits C, number of 1s in binary, bitwise AND, C bit manipulation, right shift, count bits using loop

Comments

Popular Posts

πŸŒ™