This is a C++ Program to Convert a Number in Binary Representation to Gray Code.
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.
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.
Here is the source code of C++ Program to Convert a Number in Binary Representation to Gray Code. The program output is shown below.
using namespace std;
int main ()
int num, temp, x, y, i = 0, bin =0;
cout << "Enter a binary number : ";
cin >> num;
temp = num;
while (temp != 0)
x = temp % 10;
temp = temp / 10;
y = temp % 10;
if ((x && !y) || (!x && y))
bin = bin + pow(10, i);
cout << "\nGray code of " << num << " is : " << bin;
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.
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.