Decimal to Binary number

Here is a program to convert decimal to binary-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
 
using namespace std;
 
void binary(int);
 
int main(void) {
    int number;
 
    cout << "Please enter a positive integer: ";
    cin >> number;
    if (number < 0)
        cout << "That is not a positive integer.\n";
    else {
        cout << number << " converted to binary is: ";
        binary(number);
        cout << endl;
    }
}
 
void binary(int number) {
    int remainder;
 
    if(number <= 1) {
        cout << number;
        return;
    }
 
 
    remainder = number%2;
    binary(number >> 1);
    cout << remainder;
}


I'm in a bit difficulty to understand the function binary().

Say, I would like to convert Decimal 11 to binary number. binary(number >> 1) uses bit-wise operation and generates values 5,2 and 1.For the number 11, its goes to the binary ()function recursively with with 5 then, 2 and 1. My question is then it should print the binary as 1101 with reminder output, right ? But, its prints the true value 1011. Also, after the term
remainder = number%2, every-time due to recursion its again go in the top to use the function. How the cout << remainder; able to print ?

The answer will help me a lot. Thanks :)
Last edited on
Wow, i just started to try and accomplish the same goal.
Slightly different method though... Im going to keep working on mine and get back to you, good luck!
Haha.. Cool. Very less reply today. Is this for weekend and people are still sleeping ?
Last edited on
why are you using recursion ??? can be done without ...
Recursion is important when you intend to use the same function repeatedly, such as in a game.

Coming back on topic, I can see an error.

1
2
int main(void) /* this declaration is not good for what you try to achieve 
                                     (from my knowladge) */


If I'm right you just told the c++ compilator that the main function will return void (=nothing).
Last edited on
Also, dont use this in function.

cout << variable;

Instead, you could use:

return variable;

But if you will use return variable; you will need to declare the current function with a specific type, so not void. Declaring the function as void, you cannot return anything. So that is another error on your line 26. Let me give you an example:

1
2
3
4
5
6
7
8
9
10
11
12
int binary(int number) {
    int remainder;
 
    if(number <= 1) {
        return number;
    }
 
 
    remainder = number%2;
    binary(number >> 1);
    return remainder;
}
Last edited on
Thanks all.
Topic archived. No new replies allowed.