Rust Program to Display Fibonacci Series


Display Fibonacci Series

Rust Programming Language


Display Fibonacci Series


Problem


Rust program that displays the Fibonacci series up to a given number of terms.

Input


use std::io;

fn main() {
    println!("Please enter the number of terms:");

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    let num_terms: u32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            println!("Invalid input, please enter a valid number of terms");
            return;
        }
    };

    let mut first = 0;
    let mut second = 1;

    println!("Fibonacci series up to {} terms:", num_terms);

    for _i in 1..=num_terms {
        println!("{}", first);
        let temp = first + second;
        first = second;
        second = temp;
    }
}{codeBox}

Output


Please enter the number of terms:
10
Fibonacci series up to 10 terms:
0
1
1
2
3
5
8
13
21
34{codeBox}

Explanation


In this example, we first use Rust's standard library's io module to read input from the user. We print a prompt to the console using println!("Please enter the number of terms:");.

We then create a new String called input and use the stdin() function from the io module to read a line of input from the user into input.

We then use Rust's match expression to parse the input string into an unsigned 32-bit integer. If the parsing is successful, we store the resulting integer in a variable called num_terms and continue executing the program. If the parsing fails, we print an error message and return early using return;.

We then initialize two variables, first and second, to 0 and 1, respectively. These variables represent the first two numbers in the Fibonacci series.

We then print a message indicating that we are displaying the Fibonacci series using println!("Fibonacci series up to {} terms:", num_terms);.

Finally, we use a for loop to display the Fibonacci series up to the specified number of terms. We loop from 1 to num_terms using for _i in 1..=num_terms and print each number in the series using println!("{}", first);. We then update the values of first and second so that the next number in the series can be calculated.

This shows the program prompting the user for input, the user entering the number of terms 10, and the program displaying the Fibonacci series up to 10 terms.



Post a Comment