Firstly, in version 1, not all control paths return a result as expected by the prototype int base2(int);
The second version will never reach line 9. Unless u can guarantee that num/2 will eventually equal to 0, base2(num/2) will be called recursively in a forever loop that has no way of breaking...
Your first code has error as it doesn't return anything if the num is not equal to zero
1 2 3
int base2(int num){
return something ;
}
The function must return an integer in any case.
The second code will pass the value (num/2) to the function and its answer will be returned in the end. Still , there are errors in your code .
The correct code may be like following :
1 2 3 4 5 6 7
int base2(int num){
if( num ==0)
return 0;
elsereturn base2(num/2);
}
For example : If the value of num is 2 ,else part will be executed ie num/2 will be 1 . 1 is passed to the base2() and then 1/2 will be passed to base 2 on next execution. The answer is zero , I guess :P
if you don't understand the functioning of a loop , take a pen and paper and try to note down 2 0r 3 steps . You will understand its functioning.
The line cout << num%2; will never execute if written after return . Just remember it like this 'No statement after return executes when the control has returned to the caller.'