×

Java Programs

Java Practice

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

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

Problem statement

In this program, we will read a string that contains a binary number from the user, and then we will convert it to a decimal number using recursion.

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

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

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

import java.util.*;

public class Main {
  public static int binToDec(String bin, int index) {
    int len = bin.length();

    if (index == len - 1)
      return bin.charAt(index) - '0';

    return ((bin.charAt(index) - '0') << (len - index - 1)) + binToDec(bin, index + 1);
  }

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

    String bin;
    int res;

    System.out.printf("Enter binary number: ");
    bin = X.next();

    res = binToDec(bin, 0);
    System.out.printf("Decimal number is: " + res);
  }
}

Output

Enter binary number: 10111001
Decimal number is: 185

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 binToDec(), main(). The binToDec() is a recursive method that converts a binary number into a decimal 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 binToDec() method to convert the binary number to a decimal number and printed the result.

Java Recursion Programs »





Comments and Discussions!

Load comments ↻





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