0

I am writing a simple decimal to binary converter for a homework project and ran into an issue.

The assignment specifically calls for the use of recursive functions, and I got the math and everything right - it's just that the function outputs everything in reverse:

#include <iostream>

using namespace std;

void decToBinary(int, int);

int main() {
    int asd = 0;

    cout << "Enter a non-negative intger value:  ";
    cin >> asd;

    cout << "Decimal " << asd << " = ";

    decToBinary(asd, 0);

    system("pause");
}

void decToBinary(int val, int remainder) {
    if (val == 0) {
        cout << remainder << " Binary" << endl;
    } else {
        cout << remainder;
        decToBinary(val / 2, val % 2);
    }
}

I am genuinely confused as to why this is. It seems to output everything in reverse, so for example instead of 13 being 1101 - it's 01011. The assignment requires that the remainder and the value be passed as arguments.

6
  • 3
    It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: How to debug small programs Commented Mar 28, 2018 at 21:38
  • The remainder is the last digit. You print the remainder, then you call the function recursively, so it prints the last digit before repeating. Commented Mar 28, 2018 at 21:43
  • It outputs everything in reverse because that's exactly what you asked it to do. Consider what you do before recursive call, and what may happen if you do it after instead. Commented Mar 28, 2018 at 21:43
  • Does the language guarantee the order of param eval? "decToBinary(val / 2, val % 2);" Try test case: asd = 0x222; Commented Mar 28, 2018 at 23:31
  • I think it is inappropriate to display the same result for different integer sizes (with the same value), int8_t, int16_t, int32_t, int64_t (and these same sized uintxx_t). The 0's really are part of the integer, and should also be shown. Commented Mar 28, 2018 at 23:37

1 Answer 1

1

You could do something like this:

void decToBinary(int val, int remainder)
{
    remainder = val % 2;
    val /= 2;
    if (val || remainder)
    {
        decToBinary(val, val);
        cout << remainder;
    }
}

You'll have to handle the 0 case separately.

Sign up to request clarification or add additional context in comments.

Comments

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.