循环怎么代替递归,请举三个例子,用C#代码显示,加注释帮助理解
时间: 2023-06-06 15:04:52 浏览: 90
语言实现。
循环可以代替递归,可以通过for、while和do-while等循环结构实现。
举例子:
1. 阶乘计算
递归方式:
```
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
```
循环方式:
```
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
```
2. 斐波那契数列
递归方式:
```
int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
```
循环方式:
```
int fibonacci(int n) {
int a = 0, b = 1, c;
if (n == 0) {
return a;
} else if (n == 1) {
return b;
} else {
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
```
3. 反转字符串
递归方式:
```
void reverseString(char * s, int left, int right){
if(left >= right){
return;
}
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
reverseString(s, left + 1, right - 1);
}
```
循环方式:
```
void reverseString(char* s, int sSize){
int left = 0, right = sSize - 1;
while(left <= right){
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
left++;
right--;
}
}
```
阅读全文