1

I am looking for some brief explanations on how the below program or code works.Thanks

public void Convert( int iNum )
{
    int m = 0;
    if (iNum == 1 )
        System.out.print( iNum );
    else
    {
        m = iNum % 2;
        Convert(iNum/2);
        System.out.print(m);
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

2 Answers2

2

This program tries to convert a decimal number to binary using recursion. Lets take an example:

Decimal 5 -> Binary 101

Convert(5):
m = 5 %2 -> 1
   Convert(2):
       m -> 2%2 -> 0
       Convert(1)
          The first if is true: -> 1

Output: 101 
Chander Shivdasani
  • 9,878
  • 20
  • 76
  • 107
0

It is a simple recursive call The if part will get executed only once ie, when inum=1; The else part keeps only calling convert (each time cutting the value of inum by 2) and when we cannot further dive inum first the if part gets executed and the step back to the next stacked recursive version and prints the remainder we get on dividing inum/2.

Ajay nath
  • 133
  • 2
  • 10
  • thanks ajay. so in order to have the output the we NEED to pass in a value for iNum. is that right ? –  Dec 21 '11 at 00:48