Rust Function: Calculate factorial of a number
Rust Functions and Control Flow: Exercise-4 with Solution
Write a Rust function to calculate the factorial of a given number.
Sample Solution:
Rust Code:
// Define a function named 'factorial' that takes a non-negative integer as input and returns its factorial
fn factorial(n: u64) -> u64 {
// Base case: Factorial of 0 is 1
if n == 0 {
return 1;
}
// Recursive case: Calculate factorial using recursion
n * factorial(n - 1)
}
fn main() {
let n = 5; // Define the number for which factorial is to be calculated
// Call the 'factorial' function with the specified number
let result = factorial(n as u64);
// Print the factorial of the number
println!("Factorial of {} is: {}", n, result);
}
Output:
Factorial of 5 is: 120
Explanation:
Here's a brief explanation of the above Rust code:
- 'fn factorial(n: u64) -> u64 { ... }': This is a recursive function named 'factorial' that takes a non-negative integer 'n' as input and returns its factorial as a 'u64' (unsigned 64-bit integer). The function calculates the factorial using recursion.
- Base case: If 'n' is 0, the factorial is defined as 1. Therefore, if 'n' equals 0, the function immediately returns 1.
- Recursive case: If 'n' is greater than 0, the function recursively calls itself with 'n-1' and multiplies the result by 'n'.
- 'fn main() { ... }': This is the program's entry point.
- 'let n = 5;': This line defines the number for which the factorial is to be calculated.
- 'let result = factorial(n as u64);': This line calls the 'factorial' function with the specified number ('n') and stores the result in the variable 'result'.
- 'println!("Factorial of {} is: {}", n, result);': This line prints the factorial of the number along with the original number.
Rust Code Editor:
Previous: Rust Program: Find maximum and minimum in array.
Next: Rust Function: Reverse a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-functions-and-control-flow-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics