# Thread: Printing total of 1's in binary number

1. ## Printing total of 1's in binary number

I'm writing a program where the user enters an integer and the program should tell them how many ones are in the binary form of the number. In the function I wrote, i need to use recursion. Here is what i have so far:
#include <stdio.h>

int binary( int, int );

int main()
{
int number2, c;
char x='y';

while (x=='y'||x=='Y') {
scanf("%d", number2);
printf("Number of one bits in Binary: %d\n", binary(number2));
printf("Would you like to do another? ");
scanf("%c", x);
}
}

int binary( int number, int count2 )
{
int count;
if (number==0)
return count;
else
binary(number/2, count+number % 2)
count++;
}
Now I know i may be way off base here w/ what I have but please be gentle and dont give me crap. Atleast I posted some code. Any help anyone can offer me, would be greatly appreciated. Thank you

2. Compare the following code to your original.....
The main problem was with your 'scanf' calls, you have to pass to 'scanf' the address of the variable where you want it to store the result..........

#include <stdio.h>

int binary( int, int );

int main()
{
int number2, c;
char x;

do
{
scanf("%d", &number2);

printf("Number of one bits in Binary: %d\n\n\n", binary(number2,0));

printf("Would you like to do another? ");
do
{
scanf("%c", &x);
x = toupper(x);
} while ( (x != 'Y') && (x != 'N') );

} while ( x != 'N' );

return 0;
}

int binary( int number, int count )
{
if ( number==0 ) /* no more bits are set */
{
return count;
}
else /* we have some more bits somewhere */
{
if ( number % 2 ) /* if number is odd then the rightmost bit is set */
count++;

return (binary(number/2, count));
}
}

3. Thank you for your help. I see how it is supposed to work now. i thank you again. and thank you for not criticizing me and givin me crap. Thank you for your help.