1、for循环和while循环的类比
package struct;
public class WhileDemo01 {
public static void main(String[] args) {
int a = 1; //初始值
while (a<=100){ //条件判断
System.out.println(a); //循环题
a+=2; //迭代
}
System.out.println("while循环结束");
//for循环 初始值//条件判断//迭代
for (int b=1;b<=100;b+=2){
System.out.println(b);
}
System.out.println("for循环结束");
}
}
拓展: 输入100.for 就会自动生成for循环语句
for (int i = 0; i < 100; i++) {
}
题目:计算0-100之间奇数和偶数的和
package struct;
public class WhileDemo01 {
public static void main(String[] args) {
//计算0-100之间奇数和偶数的和
int oddSum = 0;
int evenSum = 0;
for (int i = 0; i <= 100; i++) { //100.for
if(i%2!=0){ //奇数
oddSum+=i;
}else{ //偶数
evenSum+=i;
}
}
System.out.println("奇数的和"+oddSum);
System.out.println("偶数的和"+evenSum);
}
}
题目:用while循环或者dor循环输出1-1000之间能被5整除的数,并且每行输出3个
package struct;
public class ForDemo01 {
public static void main(String[] args) {
//用while循环或者dor循环输出1-1000之间能被5整除的数,并且每行输出3个
for (int i = 1; i <=1000; i++) {
if(i%5==0){
System.out.print(i+"\t"); //print输出不会换行
}
if(i%(5*3)==0){
System.out.println(); //println输出会换行
}
}
}
}