/**
题目2:使用 for 、while 、do-while 语句编写程序,打印 1 到 100 的和
*/
class For{
public static void main(String[] args){
//定义整型变量sum,用来存和并初始化为0
int sum = 0;
for (int x = 1; x<=100; x++){
sum = sum+x;
}
System.out.println("For: sum = "+sum);//输出1-100的和,格式为:For: sum = sum
}
}
![](https://img-my.csdn.net/uploads/201303/21/1363854148_1864.jpg)
class While{
public static void main(String[] args){
//定义整型变量sum,用来存和并初始化为0
int sum = 0;
//定义整型变了x,初始化为1
int x = 1;
//当条件小于等于100时,执行下列循环语句
while(x<=100){
sum = sum+x;
x++;
}
System.out.println("While: sum = "+sum);//输出1-100的和,格式为:While: sum = sum
}
}
![](https://img-my.csdn.net/uploads/201303/21/1363854283_7732.jpg)
class DoWhile{
public static void main(String[] args){
//定义整型变量sum,用来存和并初始化为0
int sum = 0;
//定义整型变了x,初始化为1
int x = 1;
//执行循环语句
do{
sum = sum + x;
x++;
}
//判断条件
while(x<=100);
System.out.println("D0_While: sum = "+sum);//输出1-100的和,格式为:D0_While: sum = sum
}
}
![](https://img-my.csdn.net/uploads/201303/21/1363854432_6132.jpg)