int -> binary recursion

first code
1
2
3
4
5
6
7
8
9
10
11
12
int base2(int num){
   
 
    
    if( num ==0) return 0;
   
   base2(num/2);
        
    cout << num%2;
    
    
}


if i put return front of recursive function

what is difference as first one. try to understand the mechanism

1
2
3
4
5
6
7
8
9
10
11
12
13
int base2(int num){
   
 
    
    if( num ==0) return 0;
   
    return base2(num/2); (if you put return what will happen?)
        
    cout << num%2;
    
    
}




Last edited on
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;
    else
        return 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.'
The correct code may be like following :
1
2
3
4
5
6
7
int base2(int num){
     
    if( num ==0) 
        return 0;
    else
        return base2(num/2);
}

Your program ALWAYS returns 0. This is the correct code:
1
2
3
4
5
int base2(int num)
{
       if (!num) return 0;
       return num%2+10*base2(num/2);
       }
Last edited on
Topic archived. No new replies allowed.