通过c语言代码举例讲解递归
时间: 2023-10-09 10:14:37 浏览: 51
递归是一种常见的编程技巧,它指的是一个函数可以调用自身的情况。递归函数在解决一些问题上非常有用,例如计算阶乘、斐波那契数列等等。
下面是一个简单的例子,演示了如何使用递归来计算阶乘:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n = 5;
int result = factorial(n);
printf("Factorial of %d is %d\n", n, result);
return 0;
}
```
这个例子中,factorial函数接收一个整数n作为参数,计算n的阶乘并返回结果。如果n等于0,则返回1,否则递归调用factorial函数,传入n-1作为参数,并将结果乘以n。
在main函数中,我们调用factorial函数并打印结果。
如果我们运行这个程序,将会得到以下输出:
```
Factorial of 5 is 120
```
这个例子中的递归很简单,但是递归函数可以非常复杂。递归需要谨慎使用,因为它可能会导致栈溢出或者无限循环。在编写递归函数时,一定要确保递归有终止条件,否则递归将会无限循环。
相关问题
C语言后续遍历非递归代码
以下是C语言后序遍历的非递归代码:
```c
void postOrder(TreeNode* t) {
TreeNode* node = t;
StackNode* s = initStack();
TreeNode* lastVisit = NULL;
while (node || !is_empty(s)) {
while (node) {
push(node, s);
node = node->lchild;
}
node = peek(s);
if (!node->rchild || node->rchild == lastVisit) {
printf("%c ", node->data);
pop(s);
lastVisit = node;
node = NULL;
}
else {
node = node->rchild;
}
}
}
```
C语言生成一段递归代码
#include <stdio.h>void recurse(int n){
if (n > 0){
printf("%d\n", n);
recurse(n-1);
}
}int main(){
int n = 10;
recurse(n);
return 0;
}代码运行后会输出从10到1的数字,每一个数字占一行。