当前位置:网站首页>C language explanation series -- understanding of functions (5) function recursion and iteration
C language explanation series -- understanding of functions (5) function recursion and iteration
2022-07-27 22:52:00 【Sad pig, little pig】
List of articles
Function recursion
What is function recursion ? Functions call their own programming skills, which we call recursion , Function recursion usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve , Recursive strategy only needs a few programs to describe the multiple repeated calculations needed in the problem-solving process , Greatly reduces the amount of program code . The main way to think about recursion is Simplify complex problems , Turn the big thing into a small one .
Let's demonstrate function recursion in a piece of code
#include<stdio.h>
void print(int n)
{
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
int num = 1234;
print(num);
return 0;
}
In the above code, we use recursive method , Print each bit of an integer value in sequence , So how to realize it specifically , We draw pictures , Let us have a more intuitive experience .

We say that function recursion is divided into two parts , First, we need to recurse, and then we have to return , Like the code above, we will num Pass the value of to the parameter n, Then judge if n>9 We need to call the function again and put the parameters n except 10, until n<9 When we print n%10, This process is called recursive process , Then they are returning , After one execution, return to the upper level function to complete the execution of this level function , Return to the previous function , Finally, back to our main function , end of execution .
Through the process of this code, we find , Function recursion must have two conditions
1. Function recursion requires constraints , When this constraint is met , Recursion will not continue
2. After each recursive call, it gets closer and closer to this limit
To sum up , The meaning of this restriction lies in , That is, recursive function calls cannot be made infinitely , There must be a constraint . What would happen without this constraint ?
As shown in the figure, when we remove the restriction of function recursion , The compiler will prompt us that there may be stack overflow, which is what we call dead recursion , Because every time we call a function, we will open up a memory space in the stack , When we recurse infinitely, we will always open up new memory space , And the space of our stack area is limited , So when recursion reaches a certain limit, it will appear Stack overflow—— Stack overflow .
Iteration of function
We say that loop is actually an iterative way , Then why do we already have the programming skills of recursion, which can simplify the code , There are still iterations ? What's the use ? We look for the answer in the code .
Please n Fibonacci Numbers , Fibonacci number is 1 1 2 3 5 8 13 21 34 55… The number of such permutations , We can see that starting from the third number , His value is the sum of the first two numbers .
int fib(int n)
{
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 0;
scanf("%d", &n);
int num = fib(n);
printf("%d ", num);
}
Through our analysis, we can easily write code using function recursion , It also looks very simple , There's no problem running , But when we want to ask for the first 50 When we find Fibonacci number
No number is output , That's because our code is wrong , It's not , The reason why there is no output is , We do too much double counting , It's time consuming , Believe it or not, we can calculate how many times the third Fibonacci number has been calculated
When we calculate the number 40 A Fibonacci number , The third Fibonacci number has been calculated 39088169 Time , Then how can we solve such a problem , We optimize the code .
int fib(int n)
{
int c = 1;
int a = 1;
int b = 1;
while (n > 2)
{
n -= 1;
c = a + b;
a = b;
b = c;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int num = fib(n);
printf("%d \n", num);
}
We just replace recursion with iteration , It can also meet our needs
Let's calculate again 50 Fibonacci Numbers
We can see that the results are output soon , The output result is incorrect because the number is too large .
To sum up :
1. Through the above cases, we can find , Recursion can explain the problem well , Especially those with formula type , It is clearer than non recursive
2. However, the iterative implementation of these problems is often more efficient than recursive implementation
3. When a problem is quite complex , When it is difficult to implement iteratively , At this point, the simplicity of recursive implementation can compensate for the runtime opening caused by it
pin
So what specific programming skills to use depends on our actual needs , Well, speaking of the basic knowledge of recursion and iteration , I have shared with you , Then for better understanding , I will share two typical examples of function recursion .
边栏推荐
- Possible causes of index failure
- Preparation of peptide kc2s modified albumin nanoparticles / targeting peptide GX1 modified human serum albumin nanoparticles probe
- When type= 'number' is set in the input field, remove the up and down buttons behind it
- 投资22亿美金!格科微12英寸CIS制造项目落户上海临港
- 联发科携手三星推出全球首款支持Wi-Fi 6的8K电视
- `What is the difference between SSH -y` (trusted X11 forwarding) and 'SSH -x` (untrusted X11 forwarding)?
- Data warehouse project is never a technical project
- OPPO Find X2系列发布:3K+120Hz曲面屏,DXO评分第一,顶配版6999元!
- jvm组成及内存模型
- 美国疫情扩散到28个州:苹果、微软等10多万员工在家办公,iPhone11快断货了!
猜你喜欢

Analysis on data collection and analysis of network security competition in national vocational college skill competition

浅析云原生应用安全组织架构

Jeninkins离线部署

解决ip地址访问末位奇数通偶数不通,或者偶数通奇数不通的问题(云加密机连接云服务器时遇到的问题,全程记录,希望能给大佬们灵感)

云计算服务主要安全风险及应对措施

If there is no reference ground at all, guess if you can control the impedance?

leetcode-461.汉明距离

视频人体行为检测

智能家居浪潮来袭,如何让机器看懂世界 【结尾有资料】

Jeninkins offline deployment
随机推荐
饿了么input输入框设置type=‘number‘时,去掉后面的上下按钮
Shandong football match
Multi tenant SaaS cloud platform framework
美国官员建议特朗普阻止英飞凌收购赛普拉斯
浅析云原生应用安全组织架构
七大排序之直接插入排序
4 轮拿下字节 Offer,面试题复盘
QT common operation collection
It is said that Huawei will cut the order again! Supply chain manufacturers are more difficult
PyQt5快速开发与实战 4.10 窗口绘图类控件
When type= 'number' is set in the input field, remove the up and down buttons behind it
NOI 2018 简要题解
Here comes Gree mask! Kn95 mask only costs 5.5 yuan!
解决ip地址访问末位奇数通偶数不通,或者偶数通奇数不通的问题(云加密机连接云服务器时遇到的问题,全程记录,希望能给大佬们灵感)
ADI, Shijian and Junlong technology jointly donated 2.3 million yuan to help fight the epidemic in Hubei
2022/5/17考试总结
[illustration] shake hands three times and wave hands four times - it's enough to read this article carefully
20字符短域名绕过复现
SSM integration process
传英特尔明年将采用台积电6nm EUV工艺