Write a Rust program to calculate the Fibonacci sequence up to a given number of terms.
Write a Rust program to calculate the Fibonacci sequence up to a given number of terms.
331
22-Jun-2023
Aryan Kumar
23-Jun-2023Sure, here is a Rust program to calculate the Fibonacci sequence up to a given number of terms:
Rust
This program first defines a function called
fibonaccithat takes an i32 number as input and returns a Vec of i32. The function first initializes a vector calledsequenceto the first two Fibonacci numbers, 0 and 1. Then, the function iterates through the numbers from 2 to n + 1. For each number, the function calculates the next Fibonacci number by adding the previous two Fibonacci numbers. Finally, the function returns thesequencevector.The main function of the program then calls the
fibonaccifunction with the value 10 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
fibonacci.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