Recursion is when a function indirectly or directly calls itself. Humans count in base 10; in contrast, computers count in base 2 because of the binary nature of electronics. Now, we are going to use the recursion method for this problem.
Let’s consider an example where a programmer wants to compute the sum of the first numbers. There are multiple ways to do this, but we will follow a recursive method, so the function will be as follows:
//Function Call: //Base Case:
f(n) = 1 n=1
f(n) = n + f(n-1) n>1
There are only two cases to discuss in line 11 in the Java program.
if (n == 0)
return (n % 2 + 10 * getBinary(n / 2))
Recursion is always terminated by the base case.
// Java program to demonstrate the working of// recursionclass Edpresso {public static int getBinary(int n) // generate Binary{if (n == 0)return 0;return (n % 2 + 10 * getBinary(n / 2));}// Driver Codepublic static void main(String[] args){int N = 6; // Number to findSystem.out.print(N + " in Binary: " + getBinary(N));}}