- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C/C++ Program to the Count set bits in an integer?

Counting set bits means counting 1’S of the given integer. For this, we have multiple solutions that can be applied. For this case, we have a binary number( binary representation of an integer), for which we have to count the number of 1’s off the string.

To count the number of 1’s, we will take the string, traverse each element and count all the 1’s of the string. For example, if we input 17 the output will be 2 because the binary of 17 is 10001 that contains two 1's.

Input: Enter a positive integer: 6 Output: 2

## Explanation

The binary representation of 6 is 110 which has 2 set bits

This iterative approach requires one iteration per bit. It runs through all the bits of the number. Iteration terminates when no more bits are set. In the worst case, on a 32-bit word with only the most significant bit set, it will loop through 32 iterations. This solution is the simplest one and useful if 1's are sparse and among the least significant bits.

## Example

#include <stdio.h> int main(void) { unsigned int n = 34; for (c = 0; n; n >>= 1) { c += n & 1; } printf("%d\n", c); }

- Related Questions & Answers
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- Python Program to Count set bits in an integer
- Java Program to Count set bits in an integer
- Count set bits in an integer in C++
- C# program to count total set bits in a number
- Sort an array according to count of set bits in C++
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- Count set bits in a range in C++
- Shift the bits of an integer to the left in Numpy
- Shift the bits of an integer to the right in Numpy
- C# program to count total bits in a number
- Python Count set bits in a range?
- How to count set bits in a floating point number in C?