0

I bought a Programming book at a yard sale for $2 because I've always wanted to learn how to code but don't have the money and resources for school. I've gotten through the first few chapters just fine, but I've also had the solutions to the problems I was working on. But the chapter is missing a few of the pages after the chapter summary when they start listing problems. I was wondering if you guys could help me out.

Here is the problem. Note: Needs to use a recursive function.

#include <stdio.h>
#include <stdlib.h>

void binaryPrinter(int value, int *numberOfOnes);
void print(char c);

//You do not need to modify any code in main
int main()
{
    char value;
    int result = 1;

    while(result != EOF)
    {
        result = scanf("%c",&value);

        if(result != EOF && value != '\n')
        {
            print(value);
        }
    }
}

//@hint: This is called from main, this function calls binaryPrinter
void print(char c)
{

}

//@hint: this function is only called from print
void binaryPrinter(int value, int *numberOfOnes)
{

}
4
  • 1
    are you trying to change this code to be recursive? Commented Oct 1, 2014 at 20:34
  • The book says that I need to only complete the two functions so that it prints the user input into binary, but yes I believe that one of the functions is supposed to call the others on it's own. Commented Oct 1, 2014 at 20:37
  • calling a function from another isn´t a recursion. It is possible (and easier) to do this with 1 function without recursion. Commented Oct 1, 2014 at 20:48
  • Then what is a recursive function? Commented Oct 1, 2014 at 20:55

1 Answer 1

2
void print(char c)
{
    int n = CHAR_BIT;
    binaryPrinter((unsigned char)c, &n);
    putchar('\n');
}

void binaryPrinter(int value, int *numberOfOnes)
{
    if((*numberOfOnes)--){
        binaryPrinter(value >> 1, numberOfOnes);
        printf("%d", value & 1);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

#include <limits.h> is missing.
it is missing in your code (you use CHAR_BIT without including the corresponding header)
Although I know that it is included in limits.h. I do not know adding write it whether it is allowed. It is read from stdlib.h on my system fortunately.
It is useful to other people because you gave me a note.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.