Hey all, I'm trying to write a program that converts a decimal number to a binary one. I have most of the program written, but I am having a little bit of trouble. Whenever I enter a decimal number, the program will convert it correctly to binary, however, the last number is not included in the conversion. EX: Converting 37 into binary (0100101) yields 010010 when entered into the program. I cannot tell exactly what is going wrong, perhaps someone else can take a look? BTW the program must utilize recursion to achieve this goal.
1) On line 40 you assign num1 with zero! What you wanted to do was
elseif (num1 == 0)
2) You are also dividing num1 by 2 and reassign before you even calc the remainder, that's incorrect.
3) You should never directly modify the function parameter (in this case num1), make a copy and do something with it. Also use a const to make sure the input doesn't get modified.
4) When writing a recursion function, the 1st thing you MUST do is check the exit condition. Usually you don't need to have an if / else clause either!
3) You should never directly modify the function parameter (in this case num1), make a copy and do something with it. Also use a const to make sure the input doesn't get modified.
I've not heard this before and I don't particularly agree with it.
For one thing, the parameter num1 is passed by value, it is already a copy of the original variable, so it is perfectly acceptable to change it as much as you like.
Another, even if the parameter was passed by reference, the reason is often because the whole intention is to modify the parameter.
Yes, there are some occasions when the parameter should not be changed, and it is correct to specify const in those cases, but there's no reason to do so this example.