In the previous lessons we talked about the types of functions and how to create and be called ...
In this lesson, I will review distinct type of the types of functions, and is known as "Recursive Methods ".
This means the functions that calls itself!! In some of the problems is the use of this type of function is very useful .. And of the most famous examples which was written in this kind are:
**** Factorial
**** Fibonacci Series
** Now I will explain this concept in the "Factorial" example:
To calculate the factorial of any integer n, we follow the following rule:
! n = n * (n-1) * (n-2) * ...* 1
Let's take for example the number 5:
! 5 = 5 * 4 * 3 * 2 * 1
If we write ! 5 = 5 * (4 * 3 * 2 * 1)
Factorial of the number 5 is: 5 * the Factorial of the 4
! 5 = 5 * (! 4)
Since: ! 4 = 4 * (! 3)
We can write Factorial of the 5 as follows:
! 5 = 5 * (4 * (! 3))
And therefore we can generalize the relation as follows:
! n = n * (! n -1)
Means: Factorial of n = number * Factorial of same number that is less of it.
Bearing in mind that the Factorial of any number less than or equal to 1 is the 1.
** Now let's create a function that finding a "Factorial" for any number using the concept of the function that calls itself Recursive method:
Means that the function "Factorial" will be calling from within the same function. As in the code below.
Of course, the previous function receives the number that you want to find a factorial of it and store in the variable "number", if this number is 1 or less, the factorial of it will be 1 so we wrote "return 1" .... I mean when you check this condition, the function will return the number one ...
else
If the number is greater than 1, it will count every time factorial of it as method which that we agreed to (the same number * Factorial of the number that is less than )
But Factorial of the number that is less of it, where will be calculated?
By calling the function again in red sentence referred to in previous figure, but when the call function in this time will be less the value of the parameter by 1to become the value of the variable
"number-1"
In the same way calling function itself in each time until it reaches the number one ..
If we tried the previous commands considering that number = 3, the process will be similar to the following:
Let us now write the full program, so we create the function Factorial at line 10, then we call it in line 19 from inside Main.
And send to it the number 5, and then will store the result that the function returns the "Factorial of the number 5" in the variable "result" which we'll print it after that:
Output will be as follows:
This is the end of the lesson ..
0 comments:
Post a Comment