Q:

Rust program to reverse a number using recursion

belongs to collection: Rust Functions Programs

0

In this program, we will create a recursive function to return the reverse number of a given number 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 reverse a number using recursion is given below. The given program is compiled and executed successfully.

// Rust program to reverse a number 
// using recursion

fn reverse(num:i32, len:u32)->i32{
    let x:i32 = 10;
    if len == 1{
        return num;
    }
    else{
        return (num % 10) * x.pow(len - 1) + reverse(num / 10, len-1);
    }
}

fn main() {
    let rs = reverse(1234,4);
    
    println!("Reversed number: {}", rs);
}

Output:

Reversed number: 4321

Explanation:

In the above program, we created two functions reverse() and main(). The reverse() function is a recursive function, which is used to return the reverse of a given number to the calling function.

In the main() function, we called the reverse() 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 check a given number is prime or n... >>
<< Rust program to calculate the sum of the digits of...