w3resource

Rust Program: Print Fibonacci Sequence up to Specified Terms

Rust Functions and Control Flow: Exercise-8 with Solution

Write a Rust program that defines a function to print the Fibonacci sequence up to a specified number of terms.

Sample Solution:

Rust Code:

// Define a function named 'print_fibonacci_sequence' that takes a number 'n' as input and prints the Fibonacci sequence up to 'n' terms
fn print_fibonacci_sequence(n: usize) {
    let mut fib = (0, 1); // Initialize a tuple to store the Fibonacci sequence (F(n-1), F(n))
    
    println!("Fibonacci sequence up to {} terms:", n);
    
    if n >= 1 {
        println!("{}", fib.0); // Print the first Fibonacci number (0)
    }
    if n >= 2 {
        println!("{}", fib.1); // Print the second Fibonacci number (1)
    }

    for _ in 3..=n {
        let next_fib = fib.0 + fib.1; // Calculate the next Fibonacci number
        println!("{}", next_fib); // Print the next Fibonacci number
        fib = (fib.1, next_fib); // Update the tuple to store the next Fibonacci number
    }
}

fn main() {
    let num_terms = 10; // Define the number of terms in the Fibonacci sequence

    // Call the 'print_fibonacci_sequence' function with the specified number of terms
    print_fibonacci_sequence(num_terms);
}

Output:

Fibonacci sequence up to 10 terms:
0
1
1
2
3
5
8
13
21
34

Explanation:

Here's a brief explanation of the above Rust code:

  • fn print_fibonacci_sequence(n: usize) { ... }: This is a function named "print_fibonacci_sequence()" that takes a number 'n' as input (of type 'usize', an unsigned integer) and prints the Fibonacci sequence up to 'n' terms.
  • Inside the function:
    • We initialize a tuple 'fib' to store the Fibonacci sequence, starting with the initial values (0, 1).
    • We print the message indicating the number of terms.
    • We handle the base cases (first two Fibonacci numbers) separately:
      • If 'n' is greater than or equal to 1, we print the first Fibonacci number (0).
      • If 'n' is greater than or equal to 2, we print the second Fibonacci number (1).
    • We then iterate from the 3rd term to the nth term, calculating and printing each Fibonacci number in the sequence.
  • In the main function,
    • We define the number of terms in the Fibonacci sequence ('num_terms').
    • We call the "print_fibonacci_sequence()" function with the specified number of terms.

Rust Code Editor:

Previous: Rust Function: Celsius to Fahrenheit conversion.
Next: Rust Function: Find Sum of array elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-8.php