Multilevel recursion in swift

Here we will discuss two level recursion in swift. If there is statement before the recursive function it will print in sequence & vice versa. Here is example code with print statement –

func test(currentIndex: Int) {
    if currentIndex > 2 {
        print("exit")
        return
    }
    print("before", currentIndex)
    test(currentIndex: currentIndex+1)
    print("after------- ", currentIndex)
    test(currentIndex: currentIndex+1)
    print("Final ================  ", currentIndex)
    
}

test(currentIndex: 0)
Prints-- > 
before 0
before 1
before 2
exit
after-------  2
exit
Final ================   2
after-------  1
before 2
exit
after-------  2
exit
Final ================   2
Final ================   1
after-------  0
before 1
before 2
exit
after-------  2
exit
Final ================   2
after-------  1
before 2
exit
after-------  2
exit
Final ================   2
Final ================   1
Final ================   0

Leave a Comment

Your email address will not be published. Required fields are marked *