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));
}
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
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!