Q:

Ruby program to convert the Binary number to Gray code using recursion

belongs to collection: Ruby User-defined Functions Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby User-defined Functions Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< Ruby program to convert the decimal number to bina...