数据结构与算法之递归(C++)

   递归,是我们编程时会用到的解决方法,他能让我们的程序变得简洁,并且能够实现我们想要的效果,相对比迭代来说,递归会更加的直接,而我们所说的迭代就是我们说的循环,他能实现我们用递归做的事情,递归,通俗的来说就是自己调用自己,一直调用自己的方法,去实现我们想要的效果,下面用程序说明一下

程序如下:

1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int factorial(int n);
 6 int iterite(int n);
 7 
 8 int main()
 9 {
10     int n = 5;
11     int result,result1;
12     for(int i=0; i<=n; i++)
13     {
14         result = factorial(i);
15         cout <<  i << "!=" << result << endl;
16     }
17     result = factorial(n);
18     result1 = iterite(n);
19     cout << result << endl;
20     cout << result1 << endl;
21     return 0;
22 }                                                                                      
23 
24 //递归
25 int factorial(int n)
26 {
27     if(n == 0)
28         return 1;
29     else 
30         return n*factorial(n-1);
31 }
32 
33 //迭代
34 int iterite(int n)
35 {
36     int num=1;
37     for(int i=n; i>0; i--)
38         num = num*i;
39     return num;
40 }
原文地址:https://www.cnblogs.com/tanshengjiang/p/14234636.html