Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
Write a program to count set bits in a number in c
✅ 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
whileloop to iterate through each bit of the number. - The
num & 1checks if the least significant bit (LSB) is 1. - If it is,
countis 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
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment