Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The language is C, please include comments for eveything done, thank you Reads a

ID: 668683 • Letter: T

Question

The language is C, please include comments for eveything done, thank you

Reads a positive integer n from the input .

Determines the number of ones in the binary representation of n and displays this value.

Requirements:

You may not call any external functions (e.g., from the math library).

Examples:

Supposen=2

The binary representation of 2 is10

So,the program should print something like

That number has1 one(s).

Suppose n=12

The binary representation of 12 is 1100

So, the program should print something like

That number has 2 one(s).

Supposen=31

The binary representation of 31 is 11111

So, the program should print something like

That number has 5 one(s).

Explanation / Answer

#include <stdio.h>

int main( int argc, char *argv[] )

{

int n,count = 0;

printf("Enter a number " );

scanf("%d",&n);

  

count=0;

while(n!=0){

n = n&(n-1);//n&(n-1) always eliminates the least significant 1

count++;

}

printf("Number of 1's in n is: %d",count);

  

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote