1到n的和while,do while, for三种方法
时间: 2023-11-26 11:02:48 浏览: 10
1. while循环实现1到n的和:
```
int n = 10;
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
printf("1到%d的和为:%d\n", n, sum);
```
2. do-while循环实现1到n的和:
```
int n = 10;
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= n);
printf("1到%d的和为:%d\n", n, sum);
```
3. for循环实现1到n的和:
```
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("1到%d的和为:%d\n", n, sum);
```
相关问题
用dowhile,while,for求n!
以下是三种使用do-while、while和for循环求n!的方法:
1. 使用do-while循环求n!
```java
int i = 1;
int result = 1;
do {
result *= i;
i++;
} while (i <= n);
System.out.println("The answer of n! is " + result);
```
2. 使用while循环求n!
```java
int i = 1;
int result = 1;
while (i <= n) {
result *= i;
i++;
}
System.out.println("The answer of n! is " + result);
```
3. 使用for循环求n!
```java
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println("The answer of n! is " + result);
```
C语言用 do…..while, while, for 三种循环语句求 n!的算法流程图
以下是C语言中使用do...while、while、for三种循环语句求n!的算法流程图:
1.使用do...while循环语句求n!的算法流程图:
```flow
st=>start: 开始
op1=>operation: 输入n
op2=>operation: 初始化i=1,fact=1
cond=>condition: i<=n?
op3=>operation: fact=fact*i
op4=>operation: i=i+1
e=>end: 输出fact
st->op1->op2->cond
cond(yes)->op3->op4->cond
cond(no)->e
```
2.使用while循环语句求n!的算法流程图:
```flow
st=>start: 开始
op1=>operation: 输入n
op2=>operation: 初始化i=1,fact=1
cond=>condition: i<=n?
op3=>operation: fact=fact*i
op4=>operation: i=i+1
e=>end: 输出fact
st->op1->op2->cond
cond(yes)->op3->op4->cond
cond(no)->e
```
3.使用for循环语句求n!的算法流程图:
```flow
st=>start: 开始
op1=>operation: 输入n
op2=>operation: 初始化fact=1
op3=>operation: for(i=1;i<=n;i++)
op4=>operation: fact=fact*i
e=>end: 输出fact
st->op1->op2->op3->op4->e
```