Skip to content

Instantly share code, notes, and snippets.

@de-sh
Last active April 29, 2020 18:44
Show Gist options
  • Save de-sh/a035ca6265077ffc189ef7b4ddc5001f to your computer and use it in GitHub Desktop.
Save de-sh/a035ca6265077ffc189ef7b4ddc5001f to your computer and use it in GitHub Desktop.
A program to print the Fibonacci sequence upto n numbers

Another 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

@de-sh
Copy link
Author

de-sh commented Apr 29, 2020

If you are reading the article, here is a note, I am also learning as I write, it will be wonderful if you'd also lend a hand and share what you've learnt any day!

Join us on https://t.me/keralars and discuss everything rust!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment