C++ Program to convert the Binary number to Gray code using recursion


Gray codes or reflected binary codes are a special type of binary representation of numbers in which two successive values differ in only one bit. For example, the binary equivalent of 1 and 2 are 01 and 10, here two bits are changing. But in gray code, the 1 is 01 and 2 is 11, only one bit is changing. In this article, we will see how we can convert a given binary number into its gray code equivalent by using recursion in C++.

Passing number as a decimal integer

In the first example, we are providing the number in decimal. The digits are only 0s and 1s but the number is decimal. For example, if we want to pass 6 as input, we pass 110 (one hundred and 10 in decimal) which is equivalent to 6 while representing in binary. The program also returns the output similarly.

Algorithm

  • Define a function solve(), this will take a binary number
  • if n is 0, then
    • return 0
  • end if
  • last := last bit of n
  • second_last = second last bit of n
  • if last and second last bits are different, then
    • put 1 and call solve( n cutting last bit )
  • otherwise
    • put 0 and call solve( n cutting last bit)
  • end if
  • end of solve() function

Example

#include <iostream> using namespace std; int solve( int n ) { if( n == 0 ) return 0; int last = n % 10; int second_last = (n / 10) % 10; if( (last && !second_last) || (!last && second_last) ) { return (1 + 10 * solve( n / 10 )); } return (10 * solve( n / 10 )); } int main() { cout << "Gray code for the number 2 (10) is: " << solve( 10 ) << endl; cout << "Gray code for the number 6 (110) is: " << solve( 110 ) << endl; cout << "Gray code for the number 13 (1101) is: " << solve( 1101 ) << endl; cout << "Gray code for the number 93 (1011101) is: " << solve( 1011101 ) << endl; }

Output

Gray code for the number 2 (10) is: 11
Gray code for the number 6 (110) is: 101
Gray code for the number 13 (1101) is: 1011
Gray code for the number 93 (1011101) is: 1110011

Conclusion

Gray code or reflected binary codes can be found by applying XOR operations on consecutive bits. The same thing is achieved by taking the last two bits of the given numbers, when they are not the same, call the function recursively and pass the number except the last one the result will be concatenated with 1, otherwise, concatenate with 0 and so on. In the example, we have provided our input as an integer decimal number and the output is also coming in integer decimal format. The same problem can be solved by taking string-type inputs which can be used to provide larger inputs when needed.

Updated on: 19-Oct-2022

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements