Home Backend Development PHP Tutorial A popular understanding of functions and recursion_PHP tutorial

A popular understanding of functions and recursion_PHP tutorial

Jul 14, 2016 am 10:09 AM
function Can Base right Compare understand of output return recursion difficult

Brothers who have no foundation may find it difficult to understand the recursion of functions, especially the concept of returning output in recursion and how it is returned.

The following is an example from the textbook. I will take it out and explain it based on my understanding. Hope this helps those who haven't figured it out yet.
function test($n){
echo $n."nbsp";
if($n>0){
                test($n-1);//Call the function itself.
}else{
echo "<--->";
}
echo $n."$nbsp";
}
test(3);//Call function output.
?>
The result is 3 2 1 0 <---> 0 1 2 3
What is easier for everyone to understand is the output of 3 2 1 0 in the front, but it is not very clear why the output of 0 1 2 3 in the back is.
To understand the recursive regression output, you must first figure out what a function is,
Official explanation:
A function is a named block of code that performs a specified task.
One of the reasons to use functions is:
Can improve program reusability
Reusability means it can be used repeatedly without writing the same code multiple times. It is to write the code repeatedly written in the program as a function, and then just call the function name when it is needed in other places, without having to write the same code again.
To put it simply, a function is a piece of code that has been written and a gun that has been built, and then placed in a public warehouse,
Functions with different functions have their own names [function function name(){}], just like guns with different functions also have their own names, such as rifles, sniper rifles, pistols, etc. These well-named functions and guns Everything has been written, built, and placed in the warehouse.
Then when someone wants to use a certain function, they go to the warehouse and call the name of the function [function name ()], and then take the function out and use it, just like the police go to the warehouse to get it according to different requirements of the task. Guns with different functions.
————This is the definition of function.
Usage of function:
The official name is: call such as aaa();
Popular understanding is: who (called the name of the function) came here and wrote the code given to you at this position.
My understanding is that it is replacement. The function call is a placeholder. When encountering this placeholder [aaa()], it is replaced with the placeholder [aaa()] specified by the placeholder that has been written. code in the function. Replace when encountered, and then the program continues to execute in sequential order.
Specific examples:
/*=============Warehouse containing functions (pistols)========================*/
function test($n){
echo $n."nbsp";
if($n>0){
                test($n-1);//Call the function itself.
}else{
echo "<--->";
}
echo $n."$nbsp";
}
/*=============Warehouse containing functions (pistols)======================*/
test(3); //Call the function. As I think, it encounters a placeholder and needs to replace the code in the function named test. (You can also understand it as going to the warehouse and calling it test. The gun is loaded with 3 bullets)
So the first encounter of test(3) became
/***********************Replace************************ on first call*/
echo $n."nbsp"; //At this time $n=3 there are three bullets
if($n>0){ //Judge that $n is 3 greater than 0, execute the following
test ($ n-1); // When you encounter the call function again, replace it when you encounter it (one shot of the bullet)
}else{
echo "<--->"; //Do not execute
}
echo $n."$nbsp"; // At this time $n=3, so the output is 3
/***********************Replace************************ on first call*/
/***********************Replace********************** on the second call*/
echo $n."nbsp"; //At this time $n=3 there are three bullets
IF ($ n & gt; 0) {// Judgment $ n & gt; 3 executes
                                                                                                                                                                                                                       echo $n."nbsp";
                                                                                                                                                                                                            
test ($ n-1); // When you encounter the call function again, replace it when you encounter it, (if the bullet is hit again)
                                                                                                                                                       
                                                                                                                                                                                                                                          echo "<--->"; //Do not execute
                    }
                                                                                                                                                                                                       echo $n."$nbsp";//At this time $n=2, so the output is 2
}else{
echo "<--->"; //Do not execute
}
echo $n."$nbsp"; //At this time $n=3, so the output is 3
/***********************Replace********************** on the second call*/
/***********************Replace************************ on the third call*/
echo $n."nbsp"; //At this time $n=3 there are three bullets
IF ($ n & gt; 0) {// Judgment $ n & gt; 3 executes
                                                                                                                                                                                                                       echo $n."nbsp";
IF ($ n & gt; 0) {// Judgment $ n is 2 greater than 0, execute below
                                                                                                                                                                                                                                   echo $n."nbsp";
IF ($ n & gt; 0) {// Judgment $ n is 1 greater than 0, execute below
test ($ n-1); // When you encounter the call function again, replace it when you encounter it, (one shot is hit)
                                                                                                                                                                 
echo "& lt; --- & gt;" "; // No execution
                                                                                                                                                                                                                      
echo $ n. "$ Nbsp"; // At this time $ n = 1, so output 1
                                                                                                                                                     
                                                                                                                                                                                                                                          echo "<--->"; //Do not execute
                      }
                                                                                                                                                                                                       echo $n."$nbsp";//At this time $n=2, so the output is 2
}else{
echo "<--->"; //Do not execute
}
echo $n."$nbsp"; //At this time $n=3, so the output is 3
/***********************Replace************************ on the third call*/
/***********************Replace************************ on the fourth call*/
echo $n."nbsp"; //At this time $n=3 there are three bullets
IF ($ n & gt; 0) {// Judgment $ n & gt; 3 executes
                                                                                                                                                                                                                       echo $n."nbsp";
IF ($ n & gt; 0) {// Judgment $ n is 2 greater than 0, execute below
                                                                                                                                                                                                                                   echo $n."nbsp";
IF ($ n & gt; 0) {// Judgment $ n is 1 greater than 0, execute below
                                                                                                     
                                                                                                                                                                                                                     echo $n."nbsp";
                                                                                                                                                                                                                         ​ 
test ($ n-1); // I will not replace it because it is not executed.
                                                                                                                    
echo "& lt; --- & gt;"; // Output & lt; ----- & gt;
                                                                                                                                                                                                     
echo $ n. "$ Nbsp"; // At this time $ n = 0, so output 0
                                                                                                                                  
echo "& lt; --- & gt;" "; // No execution
                                                                                                                                                                                                                         
echo $ n. "$ Nbsp"; // At this time $ n = 1, so output 1
                                                                                                                                                       
                                                                                                                                                                                                                                          echo "<--->"; //Do not execute
                    }
                                                                                                                                                                                                       echo $n."$nbsp";//At this time $n=2, so the output is 2
}else{
echo "<--->"; //Do not execute
}
echo $n."$nbsp"; //At this time $n=3, so the output is 3
/***********************Replace************************ on the fourth call*/
/*##################Finally, we get a code consisting only of if judgment statements and basic expressions############## #############*/
test(3);//Only call replacement once at the beginning;
//$n=3
echo $n."nbsp";//Output 3
if($n>0){
//test(3-1) is replaced by the following
echo $n."nbsp";//Output 2
                if($n>0){
                                                                                                                               using   using                                              
                                                                                                                                                                                   echo $n."nbsp"
                                                                                                                                                           
                                                                                                                                                                                      to
                                                                                                                                                                                                          echo $n."nbsp";
                                                                                                                                                                                                                                                                            
                                                                                                                                                                                                                     
test ($ n-1); // Not executed because it is not about 0
                                                                                                                                          
echo "& lt; --- & gt;" "; // Output & lt; --- & gt;
                                                                                                                                                                                                                         
echo $ n. "$ Nbsp"; // Output 0
                  }else{
                                                                                                                                                                                                                                                                          echo "<--->";//Do not execute
                }
                                                                                                                                                                                                                              echo $n."$nbsp";//Output 1
        }else{
                    echo "<--->";//Do not execute
        }
echo $n."$nbsp";//Output 2
}else{
echo "<--->";////Do not execute
}
echo $n."$nbsp";//Output 3
/*##################Finally got######################## ##*/
The result output in sequence according to the final code is
The output result is 3 2 1 0 <--> 0 1 2 3
The use of functions and recursion is ultimately parsed into the above code for execution,
This is what I understand about functions and recursion. In one sentence: "Originally there was no recursion in the world. As more functions appeared, there was recursion."
A little simple understanding, I hope it can help brothers who have no foundation to understand functions, understand recursion, and finally form their own ideas and ideas

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477637.htmlTechArticleBrothers without basic knowledge may find it difficult to understand the recursion of functions, especially the concept of returning output in recursion. , how it is returned. Below is an example from the textbook, take it out...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

What are the debugging techniques for recursive calls in Java functions? What are the debugging techniques for recursive calls in Java functions? May 05, 2024 am 10:48 AM

The following techniques are available for debugging recursive functions: Check the stack traceSet debug pointsCheck if the base case is implemented correctlyCount the number of recursive callsVisualize the recursive stack

See all articles