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; ...

Write a program to count set bits in a number in c

Count Set Bits in an Integer - C Program

✅ Count Set Bits in an Integer - C Program

#include<stdio.h>

int set(int num)
{
    int count = 0;
    while(num)
    {
        count += num & 1;
        num >>= 1;
    }
    return count;
}

int main( )
{
    int num, result;
    printf("Enter the number:\n");
    scanf("%d", &num);
    result = set(num);
    printf("set bits in %d is %d\n", num, result);
}
  

πŸ“˜ Explanation:

This program counts the number of set bits (i.e., bits that are 1) in a given integer.

  • It uses a while loop to iterate through each bit of the number.
  • The num & 1 checks if the least significant bit (LSB) is 1.
  • If it is, count is incremented.
  • Then the number is right-shifted by 1 using num >>= 1.
  • This continues until all bits are processed.

πŸ’» Sample Output:

Enter the number:
13
set bits in 13 is 3
  

πŸ”‘ Keywords:

C program to count set bits, bitwise AND in C, count number of 1s in binary, bit manipulation, beginner level C programs, efficient bit counting

πŸ“Œ Hashtags:

#CProgramming #SetBits #BitwiseOperators #InterviewC #CodeSnippet #TechBlog #BinaryInC #LearnToCode

Comments

Popular Posts

πŸŒ™