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() { ...

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

πŸŒ™