- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion

# 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 Articles
- 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++
- C# program to count total bits in a number
- How to count set bits in a floating point number in C?
- Python Count set bits in a range?
- Python program to count total set bits in all number from 1 to n.
- Count pairs in an array such that both elements has equal set bits in C++