能多举几个C语言迭代法的例子吗
时间: 2023-11-06 09:07:13 浏览: 83
1. 求阶乘:使用循环迭代计算阶乘。
```c
#include <stdio.h>
int main() {
int n, i, fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial of %d is %d\n", n, fact);
return 0;
}
```
2. 斐波那契数列:使用循环迭代计算斐波那契数列。
```c
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; i++) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
```
3. 素数判断:使用循环迭代判断一个数是否为素数。
```c
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d is a prime number\n", n);
} else {
printf("%d is not a prime number\n", n);
}
return 0;
}
```
4. 数组求和:使用循环迭代计算数组元素的和。
```c
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum of the elements is %d\n", sum);
return 0;
}
```
阅读全文