C++ Program to Convert Binary Code to Gray Code

This is a C++ Program to Convert a Number in Binary Representation to Gray Code.

Problem Description

The program takes a binary number and converts it into its equivalent Gray code. In Gray code, any two successive values differ only by one bit.

Problem Solution

1. A binary number is entered.
2. Using a while loop, the binary number is converted to its equivalent Gray code, using XOR operation.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Convert a Number in Binary Representation to Gray Code. The program output is shown below.

  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     int num, temp, x, y, i = 0, bin =0;
  7.     cout << "Enter a binary number : ";
  8.     cin >> num;
  9. 	temp = num;
  10.     while (temp != 0)
  11.     {
  12.         x = temp % 10;
  13.         temp = temp / 10;
  14.         y = temp % 10;
  15.         if ((x && !y) || (!x && y))
  16.             bin = bin + pow(10, i);
  17.         i++;
  18.     }
  19.     cout << "\nGray code of " << num << " is : " << bin;
  20.     return 0;
  21. }
Program Explanation

1. The user is asked to enter a binary number and it is stored in the variable ‘num’.
2. num is copied in a temporary variable ‘temp’. ‘bin’ and ‘i’ are initialized as 0.
3. Using a while loop, temp is divided by 10 and the remainder is stored in ‘x’.
4. temp is divided again and the remainder is stored in ‘y’.
5. XOR of x and y is calculated. If it is true, 10 to the power i is added to bin.
6. i is incremented.
7. The loop continues till temp is equal to 0.
8. bin is then printed which is the Gray code equivalent.

advertisement
Runtime Test Cases
Case 1 :
Enter a binary number : 011
Gray code of 011 is : 10
 
Case 2 :
Enter a binary number : 10101010
Gray code of 10101010 is : 11111111
 
Case 1 :
Enter a binary number : 1110
Gray code of 1110 is : 1001

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

🔥 Enroll Now for Free Python Certification - December 2025

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.