Write a function which, given an integer, returns the number of 1bits in its representation.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int returnBits(int);

int main(int argc, char ** argv) {

    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);
    printf("Number of 1-bits: %d", returnBits(n));
    return 0;

int returnBits(int n) {
    static int r = 0;

    if(n == 0)
        return 0;

    r += n%2;
    return r;


When you compile and execute the above program it produces the following result on Linux:

Enter an integer: 10
Number of 1-bits: 2

Brief Explanation

  • The program starts by requesting the user to input an integer.
  • Next, the inputted integer is passed to the recursive function returnBits which returns the number of 1bits in its representation.
  • A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result at the end of each iteration. More on Recursive Function
  • The return value of zero in the main function implies normal termination; non-zero values signal unusual or erroneous termination conditions.

Add comment

Security code