分别利用for循环,while循环、do while 循环进行编程。实现1到9999的和
时间: 2024-09-24 12:09:47 浏览: 32
for while dowhile_javado-while循环_
5星 · 资源好评率100%
在编程中,for循环、while循环和do-while循环都可以用来累加从1到9999的所有整数。以下是三种方法的示例:
1. **For循环**:
```java
int sum = 0;
for (int i = 1; i <= 9999; i++) {
sum += i;
}
System.out.println("Sum from 1 to 9999 using for loop: " + sum);
```
2. **While循环**:
```java
int i = 1;
int sum = 0;
while (i <= 9999) {
sum += i;
i++;
}
System.out.println("Sum from 1 to 9999 using while loop: " + sum);
```
3. **Do-while循环**:
```java
int i = 1;
int sum = 0;
do {
sum += i;
i++;
} while (i <= 9999);
System.out.println("Sum from 1 to 9999 using do-while loop: " + sum);
```
以上三种循环结构的结果是一样的,因为它们都会遍历从1到9999的所有数字并将它们加起来。
阅读全文