Rust Program: Factorial calculation
Rust Basic: Exercise-10 with Solution
Write a Rust program that defines a function that calculates the factorial of a given number and returns the result.
Sample Solution:
Rust Code:
// Define a function named 'factorial' that takes a parameter 'n' of type u64 and returns a u64
fn factorial(n: u64) -> u64 {
// Initialize the result variable with 1
let mut result = 1;
// Start a for loop to calculate the factorial
for i in 1..=n {
// Multiply the result by the current value of 'i'
result *= i;
}
// Return the calculated factorial
result
}
fn main() {
// Define a variable 'number' and assign a value to it
let number = 4;
// Call the 'factorial' function with 'number' as an argument
// Store the result in a variable named 'factorial_result'
let factorial_result = factorial(number);
// Print the result
println!("Factorial of {} is: {}", number, factorial_result);
}
Output:
Factorial of 4 is: 24
Explanation:
Here's a brief explanation of the above Rust code:
- fn factorial(n: u64) -> u64 { ... }: This line defines the "factorial()" function with the specified parameter and return type. Inside the function, it calculates the factorial of the given number 'n'.
- let mut result = 1;: This line declares a mutable variable 'result' and initializes it with the value 1.
- for i in 1..=n { ... }: This line starts a "for" loop. The loop iterates from 1 to 'n' (inclusive) and for each iteration, the current value of i is multiplied with 'result'.
- result *= i;: This line multiplies the current value of 'result' by the current value of i, effectively calculating the factorial.
- result: This line returns the calculated factorial as the result of the "factorial()" function.
- fn main() { ... }: This is the entry point of the program, where execution begins.
- let number = 5;: This line declares a variable 'number' and assigns it the value 5.
- let factorial_result = factorial(number);: This line calls the "factorial()" function with the value of 'number' as an argument and stores the result in the variable factorial_result.
- println!("Factorial of {} is: {}", number, factorial_result);: This line prints the factorial calculation result using the println! macro. It substitutes the placeholders {} with the values of 'number' and 'factorial_result', respectively.
Rust Code Editor:
Previous: Rust Program: Printing array elements.
Next: Rust Program: Variable assignment.
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://www.w3resource.com/rust/basic/rust-basic-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics