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

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 & technical discussions at Telegram SanfoundryClasses.