swift
Parameters: Int, Int
The two integers defining the lower and upper limit of the range
Returns: Returns an array of integers being the Fibonacci sequence within the range
This function in Swift allows you to find the Fibonacci numbers within a specified range. It uses iteration to generate the sequence up to the defined limit.
Greetings, programmer! Welcome to this blog post where we'll dive into writing a Swift function to generate a range of Fibonacci numbers. It's a fundamental concept, so whether you're a newbie or seasoned coder, this post will be handy. Remember, every complex application is built from small steps. Let's break it down together!
Start from initializing a zero-length array to store our Fibonacci sequence. We name this array fibonacciSequence
.
var fibonacciSequence: [Int] = []
We are going to define a function generateFibonacciNumbersRange
that takes two integer parameters: start
and end
. These limit the range in which to generate the Fibonacci numbers.
func generateFibonacciNumbersRange(start: Int, end: Int) { }
We start by populating the first two elements of the sequence, as the Fibonacci sequence always starts with 0 and 1. Then, we start a while loop that continues until the last generated number is less than or equal to end
.
func generateFibonacciNumbersRange(start: Int, end: Int) {
fibonacciSequence = [0, 1]
while fibonacciSequence.last! <= end {
let nextNumber = fibonacciSequence[fibonacciSequence.count - 1] + fibonacciSequence[fibonacciSequence.count - 2]
fibonacciSequence.append(nextNumber)
}
}
After generating the Fibonacci sequence, we filter out the numbers that fall outside the specified range.
func generateFibonacciNumbersRange(start: Int, end: Int) {
fibonacciSequence = [0, 1]
while fibonacciSequence.last! <= end {
let nextNumber = fibonacciSequence[fibonacciSequence.count - 1] + fibonacciSequence[fibonacciSequence.count - 2]
fibonacciSequence.append(nextNumber)
}
fibonacciSequence = fibonacciSequence.filter { $0 >= start && $0 <= end }
}
At the end, we have the function generateFibonacciNumbersRange
that generates the Fibonacci sequence in the specified range.
Here's the full code:
var fibonacciSequence: [Int] = []
func generateFibonacciNumbersRange(start: Int, end: Int) {
fibonacciSequence = [0, 1]
while fibonacciSequence.last! <= end {
let nextNumber = fibonacciSequence[fibonacciSequence.count - 1] + fibonacciSequence[fibonacciSequence.count - 2]
fibonacciSequence.append(nextNumber)
}
fibonacciSequence = fibonacciSequence.filter { $0 >= start && $0 <= end }
}
Generates Fibonacci sequence numbers that falls within a specified range
Learn moreThe Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence appears in many natural phenomena. In this function, we calculate Fibonacci numbers following the principle `F(n) = F(n-1) + F(n-2)`.
Learn more