Java Program to Convert Binary to Gray Code without Recursion

This is a Java Program to Convert Binary Code of a Number into its Equivalent Gray’s Code Without 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. After that we perform operations like modulo and divsion to convert it into gray code.

Here is the source code of the Java Program to Convert Binary Code of a Number into its Equivalent Gray’s Code Without 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 
  4. {
  5.     public static void main(String[] args) 
  6.     {
  7.         int a, b, x, result = 0, i = 0;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter Binary number:");
  10.         x = s.nextInt();
  11.         while(x != 0)
  12.         {
  13.             a = x % 10;
  14.             x = x / 10;
  15.             b = x % 10;
  16.             if((a & ~ b) == 1 || (~ a & b) == 1)
  17.             {
  18.                 result = (int) (result + pow(10,i));
  19.             }
  20.             i++;
  21.         }
  22.         System.out.println("Gray Code:"+result);
  23.     }
  24. }

Output:

$ javac Binary_Gray.java
$ java Binary_Gray
 
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.