Q:

Swift program to demonstrate the recursion

belongs to collection: Swift User-defined Functions Programs

0

Here, we will create a recursive function. A function calling itself is known as a recursive function call.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Swift program to calculate the factorial of a give... >>
<< Swift program to create a function with an in-out ...