Home »
Ruby »
Ruby Programs
Ruby program to convert the Binary number to Gray code using recursion
Ruby Example: Write a program to convert the Binary number to Gray code using recursion.
Submitted by Nidhi, on December 27, 2021
Problem Solution:
In this program, we will create an integer number initialized with binary value and then we will convert the Binary number to the Gray code using recursion.
Program/Source Code:
The source code to convert the Binary number to Gray code using recursion is given below. The given program is compiled and executed successfully.
# Ruby program to convert the Binary number
# to Gray code using recursion
def bin2gray(n)
if !(n>0)
return 0;
end
a = n % 10;
b= n / 10 % 10;
if (a>0 && !(b>0)) || (!(a>0) && (b>0))
return (1 + 10 * bin2gray(n / 10));
end
return (10 * bin2gray(n / 10));
end
number = 11011011;
result = bin2gray(number);
print "Gray code is: ",result;
Output:
Gray code is: 10110110
Explanation:
In the above program, we created an integer number number initialized with 11011011. Then we converted the given Binary number to the Gray code using recursive function bin2gray(). After that, we printed the result.
Ruby User-defined Functions Programs »