Any problem that can be solved by recursion can be converted into iterative (loop)
. Advantages of recursion : make the program clearer and more concise. Through recursion, more powerful functions can be achieved with less code
. Disadvantages of recursion: when the number of recursions increases, it will Consumes a lot of time and memory
Recursively calculate the factorial of 0~8
#include <iostream>
using namespace std;
long factorial(int num)
{
if(num==0)
return 1;
else
return num*factorial(num-1);
}
int main()
{
int i;
for(i=0; i<9; i++)
cout << i << "的阶乘:" << factorial(i) << endl;
return 0;
}
Calculate the factorial of 0~8 in a loop
#include <iostream>
using namespace std;
long factorial(int num)
{
int i, result=1;
if(num==0)
return 1;
for(i=num; i>=1; i--)
result*=i;
return result;
}
int main()
{
int i;
for(i=0; i<9; i++)
cout << i << "的阶乘:" << factorial(i) << endl;
return 0;
}