Java 基础进阶 13 -三大循环


1,For 循环:

/*
for 循环结构:
格式:
1,初始化条件
2,循环条件
3,迭代条件
5,循环体

for(1;2;3){
    //4
}

执行过程: 1,2,4,3,2,4,3-------4,3,2;
即 直至循环条件不满足,退出当前循环;
 */

public class TestFor {
    public static void main(String[] args) {

        System.out.println("Hello World");
        System.out.println("Hello World");
        System.out.println("Hello World");

        System.out.println("------");

        for (int i = 0; i <3; i++) {
            System.out.println("Hello World");
        }

        
        
        // 输出 100 以内的所有偶数及所有偶数的和(累加的思想) 以及偶数的个数;

        int sum = 0;   // 记录所有偶数的和
        int count = 0; // 偶数的个数
        for (int j = 1; j <=100; j++) { //100 以内的自然数的遍历;
            if (j % 2 == 0) {
                System.out.println(j);

                sum+=j;
                count++;
            }   
        }

        System.out.println("总和为:" + sum);
        System.out.println("100以内偶数的个数为:" + count);
    }
}


2,While 循环:

/*
While 循环结构:
格式:
1,初始化条件
2,循环条件
3,迭代条件
4,循环体

1
while(2) {
    4
    3
}
 */

public class TestWhile {
    public static void main(String[] args) {

        //输出 100 以内的所有偶数,及其和;
        int i = 1;
        int sum = 0;
        while (i <= 100) {
            if (i % 2 == 0) {
                System.out.println(i);
            }
            i++;
            sum += i;
        }
        System.out.println(sum);
    }
}


3,Do While 循环

public class TestDoWhile {
    public static void main(String[] args) {

        int i = 1;
        do {
            if (i % 2 == 0) {
                System.out.println(i);
            }
            i++;
        }while (i <= 100);


        //do-while 与 while 的区别
        int j = 10;
        do {
            System.out.println(j);
            j++;
        }while (j<10) ;

        //====================================
        while (j < 10) {
            System.out.println(j);
            j++;
        }

        //do-while 总得执行一次;

    }
}




猜你喜欢

转载自blog.csdn.net/u010282984/article/details/80783689