Exercise: Fibonacci Series

Let's implement the Fibonacci series using loops!

Problem Statement

Fibonacci sequence is a series of numbers where every number is the sum of the two numbers before it. The first two numbers are 0 and 1:

0 1 1 2 3 5 8 13

You must write the fib() function which takes in a positive integer, n, and returns the n-th Fibonacci number. However, instead of using recursion, your function must use any of the loops.

Sample Input

n = 7

Sample Output

8

Coding Challenge

Take some time to figure out how the recursive approach can be translated into an iterative one. Consider all edge cases that could occur.

If n is negative or zero, return -1.

If you feel stuck, feel free to refer to the solution review in the next lesson.

Good luck!

Get hands-on with 1200+ tech skills courses.