C language entry to c ++ master: c language entry function (3)

Chapter 7 Functions

The third section of the function recursive call wonderful deduction

1. Definition of function recursive call

-Call stack: a piece of system allocated to this program with special purpose memory, storage of formal parameters, function call relationships, local variables ... this memory is limited, once this memory size is exceeded, it will crash

-Definition: Call your own function in the function body, the execution function will repeatedly call your own function, and each call will enter a new layer

The following algorithm will have an infinite loop, so you call your own way, so you must define the exit (recursive end condition) so that the recursive call can end.

#include <iostream>

void Recursive_func() {
    printf("we are now in the Recursive_func()\n");
    Recursive_func();
}

int main() {
    std::cout << "Hello, World!" << std::endl;
    Recursive_func();
    return 0;
}

2. Exit from recursive calls

  • An example: find the factorial
#include <iostream>

//计算5的阶乘 1*2*3*4*5
int Factorial_func(int i) {
    int result;//保存阶乘结果
    if (i == 1) {
        return 1;//这里就是递归调用函数的出口
    } else {
        result = Factorial_func(i - 1) * i;
    }
    return result;
}

int main() {
    std::cout << "Hello, World!" << std::endl;
    int res = Factorial_func(5);
    printf("Factorial_func result: %d", res);
    return 0;
}

3. Must recursion be used? The advantages and disadvantages of recursion

Advantages of recursion:

  • Less code, the code looks concise and subtle

Disadvantages of recursion:

  • Not easy to understand
  • If the level of the call is too deep, the call stack may overflow. If this happens, it means that the problem cannot be solved recursively.
  • Efficiency and performance are not high, deep calls, a lot of things to be saved, so efficiency and performance cannot be high

Some problems do not need to be recursive, some problems may have to be solved recursively: Hanoi Tower

Problems with direct and indirect calls to recursive functions

  • Recursive function call directly: the process of calling the function f, the function f calls itself
  • Indirect call of recursive function: In the process of calling function f1, function f2 is called, and function f1 is called in function f2
Published 359 original articles · praised 248 · 660,000 views

Guess you like

Origin blog.csdn.net/Felaim/article/details/105666026