![]() ![]() This article has covered all the explanations and examples for finding the factorial of a number using PHP. 'The factorial of the number '.$input.' is '. ![]() In the following program, we have used recursion, the recursion is applied to the number which is the input from the user in this example. Within this function if the input is greater that one, then the same function is called again and if the input is less than or equal to 1 then one is returned. The main logic is wrapped in a function name Factorial_Function. In the following example, we will use recursion and find the factorial of the number using PHP code. We know that recursion is calling a function within a function. Here the name of the function is Factorial_Function which finds the factorial of number 8.Ĭode: //example to calculate factorial of a number using functionĮcho 'Factorial of the number 8 is '.$result Here we have enclosed the main logic in a function and then called that function to calculate the factorial of the given number in PHP. In the above two programs, we didn’t wrap the logic within a function. If the user inputs a positive number through the input box in the form, the factorial of that number is calculated and the result is printed.Įcho ''. So now the same logic is used with an input form. Followed by that is the PHP code to iterate for loop wherein all the logic is present, which we learned in the previous program. The submit button is used to submit the form data. In the below program, we have used a simple HTML form with an input text and a submit button. multiply each number up to 5 by its previous consecutive numberĮcho ''. This for loop is iterated on the sequence of numbers starting from the number till 1 is reached. In the following PHP program factorial of number 5 is calculated. A recursive function calls itself within the function. What is recursion? When a function calls itself is termed as recursion. Like other languages PHP also supports Recursion. Like using recursion, recursion with user input, without recursion, without recursion with user input. We will learn further using different methods to calculate factorial of the given number using PHP code. Get the multiplication of all the numbers.Get all the numbers starting from 1 up to that number.Get the number whose factorial is to be calculated.The logic behind getting the factorial of the number is as per the following. Now how do we actually find the factorial, we can do it using For example, the factorial of number 5 is:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |