swift

Find-nth-Fibonacci-Number()

Parameters: n: Int

The position of the Fibonacci number

Returns: Nth Fibonacci number

The function calculates the Fibonacci sequence up to the nth number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones.

Variables
Conditionals
Loops
Functions
Recursion
Medium dificulty

Swift Programming: Writing the Function to Find the Nth Fibonacci Number

Hello, fellow programmer! Today we'll be digging into something quite interesting. In this guide, we will walk through the steps needed to create a function in Swift that finds the nth number in the Fibonacci sequence. This might seem like a challenging task at first, but we assure you, once we break it down step by step, it will become much simpler. By the end, you'll have mastered another aspect of Swift. So, let's dive in and start coding!

Step 1: Understand the Problem

The problem is to generate the nth Fibonacci number. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two. For example, the first 5 numbers in the Fibonacci sequence are: 0, 1, 1, 2, 3. We will solve this problem using a recursive approach in Swift.


// Function to find nth Fibonacci number
func fibonacci(n: Int) -> Int {
  if n <= 1 {
    return n
  }
  return fibonacci(n: n-1) + fibonacci(n: n-2)
}

print(fibonacci(n: 5))  // it would print 5th Fibonacci number

Step 2: Identify Base Cases

Our base cases are when n is 0 or 1. In these cases, we simply return the value of n because the 0th Fibonacci number is 0 and the 1st is 1.

Step 3: Recursive Case

For n greater than 1, we return the sum of the (n-1)th and (n-2)th Fibonacci numbers. This is implemented as a recursive function call in our function.

Step 4: Call the Function

We can now test our function by calling it with different values of n.

Conclusion

In conclusion, the problem of finding the nth Fibonacci number can be solved using a recursive function in Swift. The implementation involves identifying the base and recursive cases for the problem. Our recursive definition comes directly from the definition of the Fibonacci sequence, namely F(n) = F(n-1) + F(n-2), and base cases F(0) = 0, and F(1) = 1.

Here's the full code once again for reference:

func fibonacci(n: Int) -> Int {
  if n <= 1 {
    return n
  }
  return fibonacci(n: n-1) + fibonacci(n: n-2)
}

print(fibonacci(n: 5))  // it would print 5th Fibonacci number

Learn function in:

Fibonacci Sequence

Sequence where each number is the sum of the two preceding ones

Learn more

Mathematical principle

The Fibonacci Sequence follows the recurrence relation F(n) = F(n-1) + F(n-2), with seed values F(0) = 0, F(1) = 1. Based on these seed values, each subsequent number is the sum of the previous two numbers. For instance, the beginning of the sequence goes as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 , etc.

Learn more