Skip to main content

Featured

C Pattern Programs: Square Number and Alphabet Patterns Explained

πŸ”· Square Star Pattern πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("* ");//keep"* " } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Column-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = num; i >= 1; i--) { for(int j = num; j >= 1; j--) { printf("%c ", j + 64);//%c for Character and 64 will be ASIIC VALUE } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Row-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; ...

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

πŸŒ™