Sure, here is a Rust function to find the factorial of a given number iteratively in Rust:
Rust
fn factorial(n: i32) -> i32 {
let mut factorial = 1;
for i in 1..=n {
factorial *= i;
}
return factorial;
}
fn main() {
let n = 5;
let factorial = factorial(n);
println!("The factorial of {} is {}", n, factorial);
}
This function first defines a function called factorial that takes an i32 number as input and returns the factorial of the number. The function uses an iterative approach to calculate the factorial. The function starts with a factorial of 1. Then, it iterates through the numbers from 1 to n, multiplying the factorial by each number. The final value of the factorial is returned.
The main function of the program then calls the factorial function with the value 5 as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called factorial.rs and then compile it using the following command:
Code snippet
rustc factorial.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./factorial
This will print the following output to the console:
Code snippet
The factorial of 5 is 120
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to find the factorial of a given number iteratively in Rust:
Rust
This function first defines a function called
factorialthat takes an i32 number as input and returns the factorial of the number. The function uses an iterative approach to calculate the factorial. The function starts with a factorial of 1. Then, it iterates through the numbers from 1 to n, multiplying the factorial by each number. The final value of the factorial is returned.The main function of the program then calls the
factorialfunction with the value 5 as input. The result of the function call is then printed to the console.To run the program, you can save it as a file called
factorial.rsand then compile it using the following command:Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet