Java Program to Print Binary Equivalent of an Integer using Recursion

This is a Java Program to Print Binary Equivalent of an Integer using Recursion.

Enter any integer number as an input. After that we pass the given number to the other function where by using modulo operator along with recursion we get the reverse of a number as an output.

Here is the source code of the Java Program to Print Binary Equivalent of an Integer using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Binary_Recursion 
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter the number:");
  9.         n = s.nextInt();
  10.         Binary_Recursion obj = new Binary_Recursion();
  11.         String m = obj.Binary(n);
  12.         System.out.println("Answer:"+m);
  13.     }
  14.     String Binary(int x)
  15.     {
  16.         if(x > 0)
  17.         {
  18.             int a = x % 2;
  19.             x = x / 2;
  20.             return a + "" + Binary(x);
  21.         }
  22.         return "";
  23.     }
  24. }

Output:

$ javac Binary_Recursion.java
$ java Binary_Recursion
 
Enter the number:19
Answer:11001

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.