The source code to demonstrate the recursion is given below. The given program is compiled and executed successfully.
// Swift program to demonstrate the recursion.
import Swift
func MyFun(val:Int)->Int{
if val == 0 {
return val
}
else {
print(val)
}
return MyFun(val:val-1)
}
MyFun(val:5)
Output:
5
4
3
2
1
...Program finished with exit code 0
Press ENTER to exit console.
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
import Swift;
Here, we created a recursive function MyFun() to print numbers from 5 to 1 on the console screen. And, we decrease the value of parameter val in every recursive call.
Program/Source Code:
The source code to demonstrate the recursion is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
Here, we created a recursive function MyFun() to print numbers from 5 to 1 on the console screen. And, we decrease the value of parameter val in every recursive call.
need an explanation for this answer? contact us directly to get an explanation for this answer