What is Recursive Function?
Recursive function is a block of code that calls itself again and again until the break condition is satisfied.
Important aspects of Recursive Function:
- A looping block (E.g., for-loop)
1.1 Write a loop that will iterate the topmost collection
1.2 An If condition, Inside this if-condition, break the loop when the required condition is satisfied
1.3 An else condition to call the recursive function in order to loop through the child collection
- A recursive function that calls itself when the break condition is not satisfied
2.1 Write a loop that will iterate the child collection
2.2 An If condition, Inside this if-condition, break the loop when the required condition is satisfied
2.3 An else condition to call the self function in order to loop through the child collection
Sample Code:
import UIKit
let arr1 = [1,2,3,4,5]
let arr2 = [6,7,8,9,10]
let arr3 = [11,12,13,14,15]
let arr4 = [16,17,18,19,20]
let arr5 = [arr1, arr2, 26, 27]
let arr6 = [arr3, arr4, 28]
let arrMain = [arr5, arr6, 21, 22, 23, 24, 25]
var compareNumber:Int = 5
var foundNumber:Int = 0
func recurringFunc(numbers: NSArray) -> Void {
for number in numbers{
"the number is \(number)"
if number is Int{
if number.isEqual(compareNumber){
foundNumber = number as Int;
break
}
}
if number is NSArray{
"the number is \(number)"
recurringFunc(number as NSArray)
}
}
}
for numbers in arrMain{
numbers
if numbers is Int{
"the number is \(numbers)"
if numbers.isEqual(compareNumber){
foundNumber = numbers as Int;
break
}
}
if numbers is NSArray{
"the number is \(numbers)"
recurringFunc(numbers as NSArray)
}
}
foundNumber