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
C Program to Count Total Set Bits in an Array
✅ C Program to Count Total Set Bits in an Array
#include <stdio.h>
int countSetBits(int num) {
int count = 0;
while (num > 0) {
count += (num & 1); // check last bit
num >>= 1; // right shift
}
return count;
}
int main() {
int n;
printf("Enter size of array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int totalBits = 0;
for (int i = 0; i < n; i++) {
totalBits += countSetBits(arr[i]);
}
printf("Total number of set bits in the array = %d\n", totalBits);
return 0;
}
๐ Explanation:
This C program counts how many set bits (1s) appear in the binary representation of all elements in an array.
countSetBits()checks each bit usingnum & 1and shifts right until the number becomes 0.- The array elements are input by the user.
- Each element’s set bits are added to
totalBits. - The final result is displayed.
๐งพ Sample Output:
Enter size of array: 4 Enter 4 elements: 5 7 8 3 Total number of set bits in the array = 8
๐ Keywords:
C program set bits, bitwise AND, right shift operator, count 1s in array, binary representation in C, coding interview C
๐ Hashtags:
#CProgramming #BitManipulation #SetBits #InterviewQuestion #LearnC #CodingForBeginners
๐ Search Description:
This C program counts the total number of set bits in an array using bitwise operations. Efficient approach with clear explanation and sample output.
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