
Swift Interview Questions Recursion: Print numbers from 0 to n without using for loop.
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)
}
}
Leave Swift Interview Questions Recursion: Print numbers from 0 to n without using for loop. to:
Read more #swift posts
Best Posts From cryptoizotx
We have not curated any of cryptoizotx's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From cryptoizotx
- Keyframe animations with Swift
- One algorithm a day: Keeping track of the largest element in a stack
- One algorithm a day. Write a function that returns best profit you could made from trading.
- One algorithm a day: floor of the square root of the input
- iOS Interview: Delegation Pattern in Swift
- Delegation Pattern in Objective-C
- Swift Interview Questions Recursion: Print numbers from 0 to n without using for loop.
- Bitwise Operators in Swift
- S O L I D Principle Rules in iOS
- Decentralized Programmer: Solidity 101