Thread: Printing total of 1's in binary number

  1. #1
    Unregistered
    Guest

    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') {
    printf("Enter your number: \n");
    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. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    6
    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
    {
    printf("\n\nEnter your number: ");
    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. #3
    Unregistered
    Guest
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program giving errors
    By andy bee in forum C Programming
    Replies: 5
    Last Post: 08-11-2010, 10:38 PM
  2. C++ program assistance needed
    By Velocity in forum C++ Programming
    Replies: 31
    Last Post: 10-05-2008, 09:08 PM
  3. Replies: 3
    Last Post: 11-25-2006, 04:14 PM
  4. Replies: 9
    Last Post: 10-07-2006, 05:37 AM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM