Thursday, August 22, 2019

Kotlin: Write a program to find the factorial of a number (Using function recursion)

In this blog, I will show you how to write a Kotlin program to find the factorial of a number.

First, we are going to write a function called 'fact' which accepts an integer as a parameter and returns an integer. So here goes the function 'fact' definition.

So how does this work? Well, in the main function we call the function 'fact' along with the integer as an argument. The function accepts it and checks if it's 1 at first, because 1! is 1 itself. If it's not one, it goes to the 'else' part where it multiplies the integer with the fact(num-1). What really happens here? When 'fact(num-1)' is called, the 'fact' function is called again, but this time, the argument is one less than the previous number. So it again works as an independent function call with (num-1) argument. This is called function recursion. This recursion occurs again and again and returns the value each time until the argument reaches 1 where it return the value 1.

For example, consider this:



Here, we give 4 as the argument for the function 'fact'. The value 4 goes inside the function and is taken by 'num'. In the 'if' condition, the 'num' is checked it it is equal to one, which it is not. So it goes to the else part and returns num*fact(num-1). Here the function calls itself, but with an argument which is 1 less than the current one. So a completely independent 'fact' function is made and multiplied with it. The same thing happens again inside the new 'fact' function with 3 as the argument. A new 'fact' function is called inside it with 2 as argument and is multiplied with it. Again a new 'fact' function with 1 as argument is made inside it, but this time it does not get multiplied with the 'fact(2)' but just returns 1. So the recursion ends there and the last returned value which got multiplied with 1 will be the final answer, which is 4*3*2*1, which equals to 24.