swift
Parameters: start: Int, end: Int
start and end define the range for the calculation
Returns: Returns the sum of even numbers within the range (provide <100 characters)
The function 'findSumEvenNumbersInRange' takes two integers as arguements (start and end of range). It then calculates the sum of all even numbers within that range and returns the result.
Hello, fellow programmer. In this guide, we will be writing a small but useful function in Swift. This function will calculate the sum of even numbers within a given range. Whether you're practicing Swift or need this function for a project, we hope that this guide serves your learning journey well. Let's start coding!
Firstly, we define a function findSumEvenNumbersRange
with two parameters: start
and end
. These parameters will specify the range in which we will search for the even numbers.
func findSumEvenNumbersRange(start: Int, end: Int) {
// function body will go here
}
Inside this function, we'll utilize Swift's stride
function to generate a sequence of numbers within the range.
func findSumEvenNumbersRange(start: Int, end: Int) {
for number in stride(from: start, to: end + 1, by: 1) {
// will check for even numbers here
}
}
In this step, we will validate if a number is even or not. In Swift, we can use the modulus operator %
to check if the remainder of the number divided by 2 is zero.
func findSumEvenNumbersRange(start: Int, end: Int) {
for number in stride(from: start, to: end + 1, by: 1) {
if number % 2 == 0 {
// number is even
}
}
}
Subsequently, we will calculate the sum of the even numbers. For this, we need to define a variable sum
before the loop starts. Then, inside the if-statement, sum up the even numbers.
func findSumEvenNumbersRange(start: Int, end: Int) -> Int {
var sum = 0
for number in stride(from: start, to: end + 1, by: 1) {
if number % 2 == 0 {
sum += number
}
}
return sum
}
Finally, we have developed a function that takes a range as input and returns the sum of all even numbers within that range. Here is the complete code.
func findSumEvenNumbersRange(start: Int, end: Int) -> Int {
var sum = 0
for number in stride(from: start, to: end + 1, by: 1) {
if number % 2 == 0 {
sum += number
}
}
return sum
}
The function is based on the arithmetic progression principle, which stats that the sum of an arithmetic series can be found using the formula `Sum = n/2 * (firstTerm + lastTerm)`. Because we only consider even numbers, we start from the first even number in the range and end at the last even number. We calculate the count of even numbers `n = (end - start) / 2 + 1` and use the formula `Sum = n/2 * (firstTerm + lastTerm)`.
Learn more