Swift program to demonstrate the recursion

Here, we are going to demonstrate the recursion in Swift programming language.
Submitted by Nidhi, on June 25, 2021

Problem Solution:

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

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.

Swift User-defined Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.