Skip to content

A program to print the Fibonacci sequence upto n numbers

A program to print the Fibonacci sequence upto n numbers

Devdutt Shenoi
Apr 29, 20201 min read

nother use of the match statement could be to handle termination conditions, this expands on what we discussed on day 1!

Here is a C function that prints the nth term of the fibonacci sequence.

int fibonacci(int n)
{
    if(n==0 || n==1) return 1;
    else return fibonacci(n - 1) + fibonacci(n - 2);
}

While we can write a similar program with if-else in rust-lang, let's see how we can oxidize it a bit more, with some match to test for termination conditions.

fn fibonacci(n: u32) -> u32 {
    match n {
        0 | 1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn main() {
    println!("The 10th term of the fibonacci sequence is {}", fibonacci(10));
}

Run in playground

Do note that we use u32, similar to unsigned int in C, for holding an unsigned 32 bit integer value, because we don't expect negative number in this problem. Expanding on the same, one can build a for loop to print the sequence of 0-nth numbe in the sequence as well.

// print 0..n elements, not inclusive of nth element
for i in 0..n {
    print!("{} ", fibonacci(i)); // without printing to newline
}
println!("{}", fibonacci(n)); // print nth element on newline

Run in playground

Did you enjoy this article?

Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.

Across the AtmosphereDiscussions