Java Reference
In-Depth Information
prints
1
; the fourth output is produced by Call 2, which prints
0
; and the fifth output
is produced by Call 1, which prints
1
. Thus, the output of the statement:
decToBin(13, 2);
is:
01101
The following Java program tests the method
decToBin
:
//*********************************************************
// Author: D.S. Malik
//
// Recursion: Program - Decimal to Binary
// This program uses recursion to find the binary
// representation of a nonnegative integer.
//*********************************************************
import
java.util.*;
public class
DecimalToBinary
{
static
Scanner console =
new
Scanner(System.in);
public static void
main(String[] args)
{
int
decimalNum;
int
base;
base = 2;
System.out.print("Enter a nonnegative integer in "
+ "decimal: ");
decimalNum = console.nextInt();
System.out.println();
System.out.print("Decimal " + decimalNum + " = ");
decToBin(decimalNum, base);
System.out.println(" binary");
}
1
3
public static void
decToBin(
int
num,
int
base)
{
if
(num == 0)
System.out.print(0);
else if
(num > 0)
{
decToBin(num / base, base);
System.out.print(num % base);
}
}
}
Search WWH ::
Custom Search