Swift program to create a simple recursive function

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write swift program to create a simple recursive function.

Recursion is a process in which a func tion call itself directly or indirectly to solve some specific task or problem. Here the function is known as recursive function and the call is known as recursive call and the recursive call always takes place inside the function not outside the function.

Recursion is helpful to reduce the length of code and make code easier to read and write. Every to recursive function required a base condition to stop a recursive function. If a recursive function does not contain any base condition then the function call itself till infinite.

Syntax

Following is the syntax of recursion function −

func myRecursion(){

   // Recursive call 
   myRecursion() 
}

Example

The following program shows how to create a simple recursive function.

import Foundation import Glibc // Function to find the factorial of a number func myfact(num: Int) -> Int{ // Base condition if (num == 0 || num == 1) { return 1 } else { // Recursive call return num * myfact(num: num - 1) } } var value = 3 print("Factorial of 3 is:", myfact(num: value))

Output

Factorial of 3 is: 6

Here in the above code, we create a function named myfact() to find the factorial of a number by recursively calling itself. Here the base condition of the recursive function is −

if(num = = 0|| num = = 1){ 
   return 1
}

When the recursive function reach to this condition then the function stops and return 1. The working of the myfact() function is −

1st call with 3: myfact(num: 3): 3 *myfact(num: 3 - 1)= 3 *myfact(num: 2)

2nd call with 2: myfact(num: 2): 2 *myfact(num: 2 - 1) = 2 *myfact(num: 2)

3rd call with 1: myfact(num: 1): 1 *myfact(num: 1 - 1)= 1 *myfact(num: 0)

Returned value from 3rd call = 1 * 1 = 1

Returned value from 2nd call = 2 * 1 = 2

Returned value from 1st call = 3 * 2 = 6

Hence the factorial of 3 is 6.

raja
Updated on 10-Oct-2022 12:38:57

Advertisements