×

Java Programs

Java Practice

Java program to convert a decimal number to its binary equivalent using recursion

Given a decimal number, we have to convert it to its binary equivalent using recursion.
Submitted by Nidhi, on June 03, 2022

Problem statement

In this program, we will read an integer number from the user, and then we will convert it to an equivalent binary number using recursion.

Java program to convert a decimal number to its binary equivalent using recursion

The source code to convert a decimal number to its binary equivalent using recursion is given below. The given program is compiled and executed successfully.

// Java program to convert a decimal number to 
// its binary equivalent using the recursion

import java.util.*;

public class Main {
  public static int decToBin(int num) {
    if (num == 0)
      return 0;
    else
      return (num % 2 + 10 * decToBin(num / 2));
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);

    int num = 0;
    int res = 0;

    System.out.printf("Enter number: ");
    num = X.nextInt();

    res = decToBin(num);
    System.out.printf("Binary number is: " + res);
  }
}

Output

Enter number: 12
Binary number is: 1100

Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods decToBin(), main(). The decToBin() is a recursive method that converts a decimal number into a binary number and returns the result to the calling method.

The main() method is the entry point for the program. Here, we read two integer numbers from the user and called the decToBin() method to convert the decimal number to binary and printed the result.

Java Recursion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.