Swift Program to get array elements after N elements


An array is used to store elements of same data type in an order. So now we extract the array elements after N elements. For example −

Array : [2, 4, 5, 6, 7, 9]

N = 3

ResultArray = [6, 7, 9]

In this article, we will learn how to write a swift program to get array elements after N elements.

Algorithm

  • Step 1 − Create function.

  • Step 2 − Create a new array using Array() initializer that containing elements after N elements.

  • Step 3 − Return the resultant array.

  • Step 4 − Create an array and a N integer from which the subarray is to be extracted.

  • Step 5 − Pass the array and N in the function and store the returned value in the new variable.

  • Step 6 − Print the output.

Example

Following Swift program to get array elements after N elements.

import Foundation
import Glibc

// Function to get array elements after N elements
func findElementsAfterN(index: Int, from array: [String]) -> [String] {
   let sArray = Array(array[index...])
   return sArray
}

// Input array
let lang = ["C#", "C", "Java", "Python", "Scala", "Perl", "Swift", "Go"]
let k = 3
let resultArray = findElementsAfterN(index: k, from: lang)
print("Elements after \(k) in the array are: \(resultArray)")

Output

Elements after 3 in the array are: ["Python", "Scala", "Perl", "Swift", "Go"]

Conclusion

Here in the above code, we create a function named ‘findElementsAfterN()’ that takes two parameters: “index” is an integer value that represent the number of elements skips before the resultant array and “lang” is an array of string from which we get the resultant array. In this function, we uses Array() initializer to create a new array that contains elements in the range [index…] from the original array. Here [index…] range means it include all the elements after the given index till the end of the array. And then this function return the resultant array that is SArray. So in the example index = 3 so the findElementsAfterN() function return all the elements present after index 3. So this is how we can get array elements after N elements.

Updated on: 08-Feb-2023

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements