以c语言编写一段程序,要求:用三种循环方式,计算自然数1到10的和。
时间: 2023-05-19 13:02:50 浏览: 77
以下是使用三种不同的循环方式计算自然数1到10的和的C语言程序:
1. 使用for循环:
```
#include <stdio.h>
int main() {
int sum = 0;
int i;
for (i = 1; i <= 10; i++) {
sum += i;
}
printf("The sum of natural numbers from 1 to 10 is %d\n", sum);
return 0;
}
```
2. 使用while循环:
```
#include <stdio.h>
int main() {
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++;
}
printf("The sum of natural numbers from 1 to 10 is %d\n", sum);
return 0;
}
```
3. 使用do-while循环:
```
#include <stdio.h>
int main() {
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 10);
printf("The sum of natural numbers from 1 to 10 is %d\n", sum);
return 0;
}
```
阅读全文