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.

import static java.lang.StrictMath.pow;

import java.util.Scanner;

public class Binary_Gray_Recursion

`{`

public static void main(String[] args)

`{`

int n, result = 0;

Scanner s = new Scanner(System.in);

System.out.print("Enter Binary number:");

n = s.nextInt();

Binary_Gray_Recursion obj = new Binary_Gray_Recursion();

result = obj.GrayCode(n, 0);

System.out.println("Gray Code:"+result);

`}`

int GrayCode(int x,int i)

`{`

int a, b, result = 0;

if(x != 0)

`{`

a = x % 10;

x = x / 10;

b = x % 10;

if((a & ~ b) == 1 || (~ a & b) == 1)

`{`

result = (int) (result + pow(10,i));

`}`

return GrayCode(x, ++i) + result;

`}`

return 0;

`}`

`}`

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.**

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

advertisement

advertisement

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

**Next Steps:**

- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Apply for Java Internship
- Apply for Information Technology Internship
- Practice Information Technology MCQs
- Practice BCA MCQs
- Buy Programming Books