Q:

Ruby program to find the HCF of two given numbers using recursion

belongs to collection: Ruby User-defined Functions Programs

0

In this program, we will read two integer numbers from the user and find the HCF of input numbers 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 find the HCF of two given numbers using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to find the HCF of 
# two given numbers using recursion

def calculateHCF(a, b)
    while a != b
        if a > b
            return calculateHCF(a - b, b);
        else
            return calculateHCF(a, b - a);
        end
    end
    return a;
end

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

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

result = calculateHCF(number1, number2);

print "HCF is: ",result;

Output:

Enter number1: 36
Enter number2: 48
HCF is: 12

Explanation:

In the above program, we read two integer numbers from the user. Then we found the HCF of input numbers using recursive function calculateHCF(). 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 calculate the product of two given... >>
<< Ruby program to find the GCD of two given numbers ...