Rust Program: Calculate nth Fibonacci number
Rust Functions and Control Flow: Exercise-6 with Solution
Write a Rust program that implements a function to calculate the nth Fibonacci number.
Sample Solution:
Rust Code:
// Define a function named 'fibonacci' that takes a non-negative integer 'n' as input and returns the nth Fibonacci number
fn fibonacci(n: u64) -> u64 {
if n == 0 {
return 0; // Base case: Fibonacci(0) is 0
} else if n == 1 {
return 1; // Base case: Fibonacci(1) is 1
}
let mut fib = (0, 1); // Initialize a tuple to store the Fibonacci sequence (F(n-1), F(n))
for _ in 2..=n {
fib = (fib.1, fib.0 + fib.1); // Update the tuple to store the next Fibonacci number
}
fib.1 // Return the nth Fibonacci number
}
fn main() {
let n = 10; // Define the value of 'n' for which Fibonacci number is to be calculated
// Call the 'fibonacci' function with the specified value of 'n'
let result = fibonacci(n);
// Print the nth Fibonacci number
println!("The {}th Fibonacci number is: {}", n, result);
}
Output:
The 10th Fibonacci number is: 55
Explanation:
Here's a brief explanation of the above Rust code:
- 'fn fibonacci(n: u64) -> u64 { ... }': This is a function named 'fibonacci' that takes a non-negative integer 'n' as input and returns the nth Fibonacci number as a 'u64' (unsigned 64-bit integer).
- Base cases: If 'n' is 0 or 1, the Fibonacci number is defined as 0 and 1 respectively. These cases are handled explicitly.
- In the iterative loop, we use a tuple 'fib' to store the Fibonacci sequence '(F(n-1), F(n))'. We start with the initial values '(0, 1)'.
- Iterate from 2 to 'n', updating the tuple in each iteration to calculate the next Fibonacci number.
- Next return the second element of the tuple 'fib' which represents the nth Fibonacci number.
- In the 'main' function, we define the value of 'n' for which the Fibonacci number is to be calculated.
- Finally we call the 'fibonacci' function with the specified value of 'n' and print the result.
Rust Code Editor:
Previous: Rust Function: Reverse a string.
Next: Rust Function: Celsius to Fahrenheit conversion.
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-functions-and-control-flow-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics