Final answer:
The Fibonacci sequence is a numeric sequence where each number is the sum of the two preceding ones. For a given index n, the fibonacci(n) function should return the nth value in the sequence, or -1 if n is negative. The value of fibonacci(7) is 13.
Step-by-step explanation:
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. To complete the fibonacci() function that returns the nth value in the sequence, one can use a simple recursive method or an iterative approach.
Here is a step-by-step explanation for an iterative approach:
- Start by checking if the index n is negative. If yes, return -1.
- Then check if n is either 0 or 1. In these cases, return n since these are the first two numbers of the Fibonacci series by definition.
- Initialize two variables to keep track of the last two numbers in the sequence. We can name them prev1 (previous number) and prev2 (the number before the previous one).
- Use a loop that starts from 2 and iterates up to n. In each iteration, calculate the new number by adding prev1 and prev2 and then update prev1 and prev2 to the last two numbers in the sequence.
- Once the loop finishes, prev1 will contain the Fibonacci number at the nth position.
If the input is 7, the output of fibonacci(7) will be the 7th number in the sequence which is 13.