Q:

Ruby program to convert the decimal number to binary using recursion

belongs to collection: Ruby User-defined Functions Programs

0

In this program, we will read an integer number from the user and get the equivalent binary number 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 decimal number to binary using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to convert the decimal number 
# to binary using recursion

def dec2bin(num)
    if num == 0
        return 0;
    else
        return num % 2 + 10 * dec2bin(num / 2);
    end
end

print "Enter number: ";
number = gets.chomp.to_i;  

result = dec2bin(number);

print "Binary equivalent is: ",result;

Output:

Enter number: 8
Binary equivalent is: 1000

Explanation:

In the above program, we read an integer number from the user. Then we converted the given decimal number to the binary using recursive function dec2bin(). Then 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 Binary number to Gray ... >>
<< Ruby program to calculate the product of two given...