For循环
100.for是for循环的高效写法,等同于for(i=0;i<100;i++)
1、for循环计算0到100之间奇数和偶数的和
2、用While循环或For循环输出1至1000之间能被5整除的数,并且每行输出3个
package test.operator;
public class forDemo01 {
public static void main(String[] args) {
//for循环计算0到100之间奇数和偶数的和
int sumOs = 0;
int sumJs = 0;
for (int i = 0; i <= 100; i++) {
if(i % 2 == 0){//偶数的和
sumOs += i;
}else{
sumJs +=i;//奇数的和
}
}
System.out.println("偶数的和:" + sumOs);
System.out.println("奇数的和:" + sumJs);
}
}
package test.operator;
public class forDemo02 {
public static void main(String[] args) {
//用While循环或For循环输出1至1000之间能被5整除的数,并且每行输出3个
int i = 1;
int j = 0;
System.out.println("========下面是While循环实现输出1至1000之间能被5整除的数,并且每行输出3个==========");
while(i <= 1000){
if (i % 5 == 0){
System.out.print(" " + i);
j++;
if(j % 3 == 0){
System.out.println();
}
}
i++;
}
System.out.println("\n" +"========下面是For循环实现输出1至1000之间能被5整除的数,并且每行输出3个==========");
int x;
int y = 0;
for (x = 1; x <= 1000; x++) {
if(x % 5 == 0){
System.out.print(" " + x);
y++;
if(y % 3 == 0){
System.out.println();
}
}
}
System.out.println("\n" + "========下面是For循环实现输出1至1000之间能被5整除的数,并且每行输出3个==========");
for (int a = 1; a <= 1000; a++) {
if(a % 5 == 0){
System.out.print(a + "\t");
if(a % (5 * 3) == 0){
System.out.println();
}
}
}
}
}