Title: Basic recursion and tail recursion
Author: MilkCu
Abstract: This article mainly describes the two basic forms of recursion: Basic recursion and tail recursion. tail recursion can improve program efficiency to a certain extent. Then, it briefly introduces the components of executable programs: code segments, static data areas, heaps, and stacks. This article describes the defects of basic recursion and the efficiency of tail recursion.
Basic Recursion
There are two basic stages of the recursive process: recurrence and regression.
Implement the function for calculating factorial in the basic recursion mode:
#include
int fact(int n){ if(n < 0) { return 0; } else if(n == 0) { return 1; } else if(n == 1) { return 1; } else { return n * fact(n - 1); }}int main(void){ printf("%d\n", fact(4)); return 0;}
Executable program composition?
Basically, an executable program consists of four areas: code segment, static data zone, heap, and stack.
The code segment contains the machine commands executed when the program is running;
The static data zone contains persistent data throughout the life cycle of the program, such as global variables and static local variables;
The heap contains the storage space dynamically allocated when the program is running, such as the memory allocated with malloc;
Stack contains information about function calls.
The stack maintains the information of each function call and guides the function to be released only after the function is returned. Therefore, the function call overhead is high. Tail recursion can be used to avoid these shortcomings.
Tail recursion?
When a recursive call is the last statement executed in the entire function and its return value is not part of the expression, this recursive call is tail recursion.
The feature of tail recursive functions is that regression functions do not need to perform any operation. Most modern compilers will use this feature to automatically generate optimized code.
Calculate a factorial function in the form of tail recursion:
#include
int facttail(int n, int a){ if(n < 0) { return 0; } else if(n == 0) { return 1; } else if(n == 1) { return a; } else { return facttail(n - 1, n * a); }}int main(void){ printf("%d\n", facttail(4, 1)); return 0;}
(Full text)
Address: http://www.milkcu.com/blog/archives/basic-recursion-and-tail-recursion.html