Concepts and examples of recursive functions

Source: Internet
Author: User

I. Stack
When talking about function recursion, let's take a look at the concept of stack.
Stack is a push and POP data structure. When the program runs, the system injects an object into the stack each time, and then the stack pointer moves down to a position. When the system pops up an object from the stack, the object that recently enters the stack will pop up. Then the stack pointer moves up a position. Programmers often use the stack data structure to deal with programming problems that are most suitable for describing the narrative with the back-to-first-out logic. The stack in the program discussed here exists in every program. It does not need to be maintained by programming, but is automatically handled by the system. The so-called system self-maintenance is actually the program code generated by the compiler. Although they are not seen in the source code, programmers should understand this.
Let's take a look at how the stack in the program works. When a function (caller) calls another function (called by the caller), the system will push all the caller's real instances and return addresses to the stack at runtime, the stack pointer is moved to an appropriate location to hold the data. At last, the caller's return address is added to the stack. When the caller starts running, the system pushes the caller's independent variables into the stack and moves down the stack pointer to ensure that there is enough space to store all the independent variables declared by the caller. After the caller pushes the real volume into the stack, the caller creates a volume in the stack as an independent variable. Other independent variables in the caller are also stored in the stack. Because of these stack operations, the stack pointer has moved all of these local variables. However, the caller recorded the initial Stack pointer at the beginning of the runtime and used it as the benchmark. The positive or negative offset value was used to explain the variables in the stack. When the caller prepares to return the result, the system displays all the independent variables in the stack. At this time, the stack pointer moves the position where the caller started running. Then, the caller returns the address from the stack, and the caller can continue running. When the caller continues running, the system will also pop up the caller's real volume from the stack, so the stack pointer is back to the position before the call.
People who have just started learning may not quite understand the above explanation. The stack involves pointer issues, so they can look at some data structures in detail. To learn the programming language well, you must learn the data structure.

Ii. Recursion
Recursion is a very important part of function implementation. Many programs use recursive functions more or less. Recursion means that the function calls itself, or calls itself in the lower-level function called by the function itself.
Recursion is implemented because every running process of a function has its own shape and copy of local variables in the stack. These copies are irrelevant to other running processes of the function. This mechanism is the basis for implementing the subprogram structure in most programming languages and makes recursion possible. Assume that a called function calls a called function, and then the called function calls the called function in turn. This second call is called the recursion of the called function because it occurs before the current running process of the called function is completed. In addition, because the previously called function and the currently called function have its independent number of arguments and independent variables at a lower position in the stack, the original number of workers and variables will not be affected, so recursion can work normally. The process of program traversal to run these functions is called recursive descent.
Programmers need to ensure that recursive functions do not change the values of static variables and global variables at will, so as to avoid upper-layer function errors during recursive descent. Programmers must also ensure that there is a termination condition to end the recursive descent process and return to the top layer.
For example, this program is recursive:

Void A (INT );

Main ()
{
Int num = 5;
A (Num );
}

Void A (INT num)
{
If (num = 0) return;
Printf ("% d", num );
A (-- num );
}

In function a (), you call yourself, that is, you call yourself. This is recursion. So some people may think, isn't this an endless loop? Therefore, there must be a return statement in a recursive function. A recursive function without a return statement is an endless loop.
We analyze the example above, first call a (5), then output 5, then call itself a (4) in the function, then return to the function start point, output 4 ,......, Until a (0) is called, it is found that the if condition has been met. Instead of calling, it returns, so this recursion is performed five times in total. If this return is absent, it must be an endless loop.
Although recursion is not hard to understand, there are many problems when using recursive functions. There are two general reasons: first, how to recursion, that is, how to take a variable for recursion, and second, how to terminate recursion, often making an endless loop.
See the following examples:
1. Calculate 1 + 2 + ...... + 100 sum
Analyze it first. For the first recursive variable problem, we should take 1, 2,... from the perspective of the question ,......, 100 the values of these variables are used as recursive conditions. The second is how to terminate them. From the perspective of the question, it should be that when the number is 100, it cannot be added down. Then we try to write the program.

Int add (INT );

Main ()
{
Int num = 1, Sn;
Sn = add (Num );
Printf ("% d/N", SN );
Getch ();
}

Int add (INT num)
{
Static int Sn;
Sn + = num;
If (num = 100) return Sn;
Add (++ num );
}

Analyze the program: Call add (1) and add this 1 to the Sn in the sub-function. Call add (2) and add Sn to 2. In this way, when we reach 100, we add the value first and then find that the if condition is met. Then, the value of Sn is returned, that is, 1 + 2 + ...... + 100.
Note that there is a problem here, that is, static int Sn;
Some people do not know why static type modifiers are used. Why not int Sn = 0 ;? Assume that int Sn = 0 is used. In each call to add () a function, the value of Sn is 0, that is, the first step is added with 1, however, in the second call, the SN returned to 0. As we mentioned earlier, static can ensure that the value of this initialization is the value after the previous operation, so that the results to be added earlier will not be lost. If you change to int Sn = 0, the final result must be the value of 100 instead of 5050.

2. Calculate the nth Number of the series S (n) = S (n-1) + S (n-2. S (1) = S (2) = 1.
We can see that the termination condition must be S (1) = S (2) = 1. The number of records for Recursive descent must be n.

Int A (INT );

Main ()
{
Int N, S;
Scanf ("% d", & N );
S = a (n );
Printf ("% d/N", S );
Getch ();
}

Int A (int n)
{
If (n <3) return 1;
Return A (n-1) + a (n-2 );
}

This topic mainly explains that in a function, there may not be only one return statement, but each pair has only one function. The question is not hard to understand. I will not analyze it here.
Speaking of this recursion, there is actually no big difference between it and the function call, mainly because a termination condition needs to be selected. Recursive functions can be processed cyclically in many cases.

Main ()
{
Int n = 20, array [20];
Int I;
For (I = 0; I <n; I ++)
{
If (I <2) array [I] = 1;
Else array [I] = array [I-1] + array [I-2];
}
Printf ("% d/N", array [19]);
Getch ();
}

The above program implements the same functions. However, it has a defect that the value of N is not obtained through keyboard input. Assume that you want to use the keyboard to obtain N, which can be as follows:

Main ()
{
Int N, I;
Int S1 = 1, S2 = 1, temp
Scanf ("% d", & N );
For (I = 3; I <= N; I ++)
{
Temp = S2;
S2 + = S1;
S1 = temp;
}
Printf ("% d/N", S2 );
Getch ();
}

In some cases, recursion is much easier than loop. There are also some questions that should be solved by recursion rather than loop at first glance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.