Jacob
Jacob

Reputation: 79

Recursive function outputs values in reverse

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.

Upvotes: 0

Views: 66

Answers (1)

Sid S
Sid S

Reputation: 6125

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.

Upvotes: 1

Related Questions