Java Program to Convert Binary to Gray Code using Recursion

This is a Java Program to Convert Binary Code of a Number into its Equivalent Gray’s Code Using Recursion. Gray code is a binary numeral system where two successive values differ in only one bit.

Enter any binary number as an input. Now we pass the gven number along wth zero to different function where with the help of different operatons like modulo,divsion and recursion we get the gray code as an output.

Here is the source code of the Java Program to Convert Binary Code of a Number into its Equivalent Gray’s Code Using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import static java.lang.StrictMath.pow;
  2. import java.util.Scanner;
  3. public class Binary_Gray_Recursion 
  4. {
  5.     public static void main(String[] args) 
  6.     {
  7.         int n, result = 0;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter Binary number:");
  10.         n = s.nextInt();
  11.         Binary_Gray_Recursion obj = new Binary_Gray_Recursion();
  12.         result = obj.GrayCode(n, 0);
  13.         System.out.println("Gray Code:"+result);
  14.     } 
  15.    int GrayCode(int x,int i)
  16.    {
  17.        int a, b, result = 0;
  18.        if(x != 0)
  19.         {
  20.             a = x % 10;
  21.             x = x / 10;
  22.             b = x % 10;
  23.             if((a & ~ b) == 1 || (~ a & b) == 1)
  24.             {
  25.                 result = (int) (result + pow(10,i));
  26.             }
  27.             return GrayCode(x, ++i) + result;
  28.         }
  29.        return 0;
  30.    }
  31. }

Output:

$ javac Binary_Gray_Recursion.java
$ java Binary_Gray_Recursion 
 
Enter Binary number:1001
Gray Code:1101

Sanfoundry Global Education & Learning Series –- 1000 Java Programs.

advertisement
advertisement

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

If you find any mistake above, kindly email to [email protected]

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.