Swift Interview Questions Recursion: Print numbers from 0 to n without using for loop.

in #swift6 years ago

This one is tricky! How can you print all those numbers with for loop, enumeration, or similar techniques that would make this task trivial?

The answer is recursion.
Most computer programming languages support recursion by allowing a function to call itself from within its own code.

You need to call the same function n times and increment variable passed as argument to it. A sample solution is presented below:


func countUp(index:Int, countTo:Int){
    if index > countTo{
        return
    }
    else{
        print(index)
        countUp(index: index + 1, countTo: countTo)
    }
}

countUp(index: 1, countTo: 10)

So how would you deal with counting it down? There are couple ways to do it. One would be using function similar to one below, where we simply decrement the variable passed as an argument:


func countDown(index:Int, countTo:Int){
    if index >= countTo{
        print(index)
        countDown(index: index - 1, countTo: countTo)
    }
    else{
        return
    }
}

I like better though another solution. We can accomplish it with simply reversing the order of statements inside the else statement of the countUp function. It also shows better how the recursive call works on adding calls on the stack! The print statement is not reached until the base condition is reached, and then one by one is calling last instruction on the stack. This will happen in reverse order to the one was called in a first place.
countUp(index:10, countTo:10) countUp(index:9, countTo:10) countUp(index:8, countTo:10)

func countDown(index:Int, countTo:Int){
    if index > countTo{
        return
    }
    else{
        countDown(index: index + 1, countTo: countTo)
        print(index)
    }
}

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 99163.21
ETH 3283.22
USDT 1.00
SBD 3.05