import java.util.Scanner;


public class DecimalToBinaryConverter {

    int numOfBinary = 8; 
    int[] binary = new int[numOfBinary]; 
    String output = ""; 
    
    
    public int fillArray(int counter) {
        if (counter == numOfBinary) {
            return 0;
        }
        binary[counter] = (int)Math.pow(2, numOfBinary - 1 - counter);
        return fillArray(counter + 1); 
    }
 
    public int decimalToBinary(int number, int counter) {
        if (counter == numOfBinary) {
            return 0; 
        }
        if (number - binary[counter] >= 0) {
            number -= binary[counter]; 
            output += "1"; 
        } else {
            output += "0"; 
        }
        return decimalToBinary(number, counter + 1); 
    }

    public static void main(String[] args) {
        DecimalToBinaryConverter number = new DecimalToBinaryConverter();
        number.fillArray(0);
        
        Scanner input = new Scanner(System.in); 
        System.out.println("What number would you like to convert to decimal?"); 
        int num = input.nextInt();

        System.out.println(num);

        number.decimalToBinary(num, 0);
        System.out.println(num + " converted to binary is: " + number.output);
        
    
    }
}
DecimalToBinaryConverter.main(null)
What number would you like to convert to decimal?
25
25 converted to binary is: 00011001

Notes

Recursive method: Method that calls itself repeatedly

  • Consists of two parts: Base case and recursive call
  • Base case: The value that is returned when the recursion stops

Recursive methods use a call stack that keeps track of the recursive function being called until the base case is reached.

Difference between recursion and iteration

Iteration executes code through a loop (ex: for loop, while loop), while recursion uses function calls

The most important thing about binary search is that the data must be sorted i.e. from least to greatest. Binary search is more efficient than linear search.

Linear recursion is when a function calls itself only once. An example is shown below.

import java.util.Scanner;


public class Demo {

    public static int addNumAndConst(int num1, int num2) {
        if (num1 == 1 && num2 == 0) {
            return num1 + num2; 
        }
        return num1 + num2 + addNumAndConst(1, 0); 
    }

    public static void main(String[] args) {
       System.out.println(addNumAndConst(5, 3)); 
        
    
    }
}
Demo.main(null)
9

Selection sort finds the minimum element and attaches it to the sorted part.

Merge sort divides the array into two halves and repeatedly does so. The merge() function is then used to merge them together.