fn fibonacci(n: i32) -> Vec<i32> {
let mut sequence = vec![0, 1];
for i in 2..n + 1 {
let next_fibonacci_number = sequence[i - 1] + sequence[i - 2];
sequence.push(next_fibonacci_number);
}
return sequence;
}
fn main() {
let n = 10;
let fibonacci_sequence = fibonacci(n);
println!("The Fibonacci sequence up to {} terms is:", n);
for number in fibonacci_sequence {
println!("{}", number);
}
}
This program first defines a function called fibonacci that takes an i32 number as input and returns a Vec of i32. The function first initializes a vector called
sequence to 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 the sequence vector.
The main function of the program then calls the fibonacci function 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.rs and then compile it using the following command:
Code snippet
rustc fibonacci.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./fibonacci
This will print the following output to the console:
Code snippet
The Fibonacci sequence up to 10 terms is:
0
1
1
2
3
5
8
13
21
34
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, 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