Loop Assignment 17 — Count the Number of 1s in the Binary Representation of an Integer Using a While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Count the Number of 1s in the Binary Representation of an Integer Using a While Loop — Counting Set Bits

📑 On this page:
  • How Set-Bit Counting Works
  • The Three Steps of Counting Set Bits
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What set bits are in the binary representation of a number
  • How to count 1s using a while loop
  • How repeated division by 2 extracts binary digits
  • How the modulo operator helps identify a set bit
  • Why this method works for positive integers
  • How to calculate the time complexity of bit counting

How Set-Bit Counting Works

A set bit is a binary digit that has the value 1. For example, the decimal number 13 is represented in binary as 1101. It contains three 1s, so it has three set bits.

To count set bits using a while loop, repeatedly divide the number by 2. In each step, number % 2 gives the last binary digit. If this remainder is 1, increase the counter. Then divide the number by 2 to remove that binary digit.

This process continues until the number becomes 0. The counter then contains the total number of 1s present in the binary representation of the original integer.

💡 In one line: Repeatedly check number % 2; if it is 1, increase the count, then divide the number by 2 until it becomes 0.

Diagram showing counting of 1s in the binary representation of an integer using a while loop

The Three Steps of Counting Set Bits

Step Operation Effect
1. Check the last bitremainder = number % 2;Gives the current binary digit, either 0 or 1
2. Count the set bitif (remainder == 1) count++;Increases the count when the binary digit is 1
3. Remove the last bitnumber = number / 2;Prepares the number for the next binary digit

For example, the binary representation of 13 is 1101. The program checks the binary digits from right to left: 1, 0, 1, and 1. Since three of them are 1, the final count is 3.

This method is simple and easy to understand. It is especially useful for beginners because it connects decimal-to-binary conversion with loop-based digit extraction.

Complete C Program

Program: count the number of 1s in the binary representation of an integer using a while loop

#include <stdio.h>

int main(void) {
    int number, remainder, count = 0;

    printf("Enter a non-negative integer: ");
    if (scanf("%d", &number) != 1 || number < 0) {
        printf("Invalid input. Please enter a non-negative integer.\n");
        return 1;
    }

    while (number != 0) {
        remainder = number % 2;   /* last binary digit */

        if (remainder == 1) {
            count++;              /* set bit found */
        }

        number = number / 2;      /* remove last binary digit */
    }

    printf("\nNumber of 1s in binary representation: %d\n", count);

    return 0;
}
                                    

Program Output

Enter a non-negative integer: 13

Number of 1s in binary representation: 3
                                

A second run, with decimal 0:

Enter a non-negative integer: 0

Number of 1s in binary representation: 0
                                

In the first run, decimal 13 has binary representation 1101, which contains three 1s. In the second run, decimal 0 has binary representation 0, so the number of set bits is 0.

Step-by-Step Explanation

Let us understand how the program counts the 1s in the binary representation of 13.

1. Initial value

The input number is 13. Its binary representation is 1101. The counter variable is initialized to 0.

2. First loop iteration

13 % 2 gives 1, so the last binary digit is 1. The counter becomes 1. Then 13 / 2 gives 6.

3. Second loop iteration

6 % 2 gives 0, so the current binary digit is 0. The counter remains 1. Then 6 / 2 gives 3.

4. Third loop iteration

3 % 2 gives 1, so the counter becomes 2. Then 3 / 2 gives 1.

5. Fourth loop iteration

1 % 2 gives 1, so the counter becomes 3. Then 1 / 2 gives 0.

6. Loop termination

The while loop stops when number becomes 0. The final counter value is 3, which is the number of 1s in 1101.

7. Why modulo 2 is used

The expression number % 2 returns either 0 or 1 for a non-negative integer. This directly gives the last binary digit of the number.

8. Why division by 2 is used

Dividing by 2 removes the last binary digit. For example, dividing binary 1101 by 2 gives binary 110. This allows the loop to examine the next binary digit in the following iteration.

9. Alternative bitwise method

The same result can be obtained using bitwise operators:

while (number != 0) {
    if (number & 1) {
        count++;
    }
    number = number >> 1;
}
                                

Here, number & 1 checks the last bit, and number >> 1 shifts the bits one position to the right. Both methods produce the same result.

10. Complexity summary

Time complexity is O(log2 n), because the number is divided by 2 in every iteration. Space complexity is O(1), because the program uses only a few integer variables.

🎯 Remember this: To count 1s in a binary number, repeatedly calculate number % 2. If the remainder is 1, increase the count. Then divide the number by 2 until it becomes 0.

Frequently Asked Questions

1. What is a set bit?

A set bit is a binary digit with the value 1. For example, the binary number 1011 has three set bits because it contains three 1s.

2. Why do we use number % 2?

number % 2 gives the last binary digit of the number. If the result is 1, the current bit is set; if it is 0, the current bit is not set.

3. Why do we divide the number by 2?

Dividing by 2 removes the last binary digit. This allows the while loop to examine the next binary digit in the following iteration.

4. What happens if the input is 0?

The while loop does not execute because the condition number != 0 is false initially. Therefore, the count remains 0, which is correct for binary 0.

5. Can this program count bits in a negative number?

This version accepts only non-negative integers. Negative numbers are stored using two's complement representation, so counting their set bits requires special handling.

6. What is the time complexity of this program?

The time complexity is O(log2 n), because the number is divided by 2 in every iteration. The space complexity is O(1), since only a few integer variables are used.

💡 Tip: After implementing this program, try printing the binary representation of the number as well. You can store each remainder in an array and print the remainders in reverse order.

📖 Related Tutorials

  • 16. Convert a Decimal Number to Octal Using a Do-While Loop
  • 18. Convert a Hexadecimal String to Decimal Using a For Loop
  • 15. Find the Sum of All Digits of a Given Number
  • All Loop Assignments in C

Previous Topic: -->> 16. Write a program in C to convert a decimal number to octal using a do-while loop.   ||   Next Topic: -->> 18. Write a program in C to convert a hexadecimal string to decimal using a for loop.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.