Exercise: Implementing the Fibonacci Series

Let’s implement the Fibonacci series using loops!

We'll cover the following

The 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

Problem statement

Your task, therefore, is to 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 loops.

You also need to keep in mind that when the input is less than one, your solution should return -1.

Input

n = 7

Output

8

Challenge

This problem has been designed for you to practice freely, so try to solve it on your own first. Take some time and think about the different concepts that have been explored in the course so far.

If you feel stuck, you can always check out the solution review provided in the next lesson.

Good luck!

Get hands-on with 1400+ tech skills courses.