Java Online Compiler
Example: Decimal to Binary Conversion using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Decimal to Binary Conversion using Recursion in Java import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive function to convert decimal to binary public static String toBinaryRecursive(int decimal) { // Base case: if the decimal number is 0, its binary is "0" if (decimal == 0) { return "0"; } // Base case: if the decimal number is 1, its binary is "1" if (decimal == 1) { return "1"; } // Recursive step: // Get the remainder when divided by 2 (this is the current binary digit) int remainder = decimal % 2; // Recursively call the function with the quotient (decimal / 2) // and prepend the current remainder to the result return toBinaryRecursive(decimal / 2) + remainder; } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a decimal number System.out.print("Enter a non-negative decimal number: "); int decimalNumber = scanner.nextInt(); // Step 3: Validate input to ensure it's non-negative if (decimalNumber < 0) { System.out.println("Please enter a non-negative number."); } else { // Step 4: Call the recursive function to convert the number String binaryRepresentation = toBinaryRecursive(decimalNumber); // Step 5: Handle the special case for input 0, as our base case for 0 returns "0" // but for other numbers, it builds up. This ensures "0" is correctly handled. if (decimalNumber == 0) { System.out.println("Binary representation: 0"); } else { System.out.println("Binary representation: " + binaryRepresentation); } } // Step 6: Close the scanner scanner.close(); } }
13
Output
Clear
ADVERTISEMENTS