ADVERTISEMENT
ADVERTISEMENT

Ruby program to calculate the product of two given numbers using recursion

Ruby Example: Write a program to calculate the product of two given numbers using recursion.
Submitted by Nidhi, on December 27, 2021

Problem Solution:

In this program, we will read two integer numbers from the user and calculate the product of input numbers using recursion.

Program/Source Code:

The source code to calculate the product of two given numbers using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to calculate the product 
# of two given numbers using recursion

def calculateProduct(a, b)
    if a < b
        return calculateProduct(b, a);
    elsif b != 0
        return (a + calculateProduct(a, b - 1));
    else
        return 0;
    end
end

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

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

result = calculateProduct(number1, number2);

print "Product is: ",result;

Output:

Enter number1: 5
Enter number2: 3
Product is: 15

Explanation:

In the above program, we read two integer numbers from the user. Then we calculated the product of input numbers using recursive function calculateProduct(). Then we printed the result.

Ruby User-defined Functions Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.