Q:

Rust program to calculate the product of two numbers using recursion

belongs to collection: Rust Functions Programs

0

In this program, we will create a recursive function to calculate the product of two integer numbers and return the result to the calling function.

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 calculate the product of two numbers using recursion is given below. The given program is compiled and executed successfully.

// Rust program to calculate the product 
// of two numbers using recursion

fn calculateProduct(a:i32, b:i32)->i32
{
    if a < b
    {
        return calculateProduct(b, a);
    }
    else if b != 0
    {
        return (a + calculateProduct(a, b - 1));
    }
    else
    {
        return 0;
    }
}

fn main() {
    let a:i32=6;
    let b:i32=8;
        
    let res = calculateProduct(a, b);
    println!("The product of {0} and {1} is {2}.", a, b, res);
}

Output:

The product of 6 and 8 is 48.

Explanation:

In the above program, we created two functions calculateProduct() and main(). The calculateProduct() function is a recursive function, which is used to calculate the product of two integer numbers and return the result to the calling function.

In the main() function, we called the calculateProduct() function and printed the result.

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to convert an integer number to binar... >>
<< Rust program to calculate the product of two numbe...