/**
题目:编写程序,打印1到100的和,分别以while、do-while、for三种方式体现
@author 郑show
*/
/*
使用for循环语句求和
*/
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
}
}
/*
使用While语句求和
*/
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
}
}
/*
使用While语句求和
*/
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
}
} |