1

i'm a complete noob in c++ and we had to do a programm in school that calculates the cross sum of a number and then convert this number to a binary number.

The problem I have now is that the binary number is in reverse order. I want to add the digits into an array and then cout the array from right to left, but I do not have any Idea how to do it. :/

Could someone explain / show me how to do it?

And I am using the do while loops because that was the requirement for the task...

int main()
{
    int digit, sum = 0, rem;

    cout<<"Enter a positive digit" << endl;
    cin >>  digit;

    do {
        sum= sum + (digit%10); 
        digit /= 10;
    }
    while (digit!= 0);

    cout <<"Cross sum" << sum << endl; 

    do {
        rem = sum % 2;
        sum /= 2;
        cout << "Decimal in Binary: " << rem << endl;
    }
    while(sum>0);

    return 0;
}

1 Answers1

0

This function will print decimal to binary in right order:

void decToBin(int n) {
    if (n == 0) {
        return;
    }
    decToBin(n / 2);
    cout << n % 2;
}
  • You may want to use right shift `operator>>` and the binary AND `operator &`. Many times more efficient than remainder and division (however compiles may recognize the pattern and make the optimization). – Thomas Matthews Sep 27 '19 at 16:30