循环语句For While do-while的小练习

时间:2020-12-31 20:27:14

 -------android培训、 java培训期待与您交流! ----------
/**题目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
}
}

循环语句For   While  do-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
}
}

循环语句For   While  do-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
}
}

循环语句For   While  do-while的小练习