8.while、do-while、for循环的区别


while、do-while、for 循环的区别

相同点

都遵循循环四要素,即初始化循环变量、循环条件、循环体、更新循环变量。

不同点

  • while 和 do-while 适用于循环次数不确定的场景;for 循环适用于循环次数确定的场景。
  • while 和 for 是先判断循环条件,再执行循环体;do-while 循环是先执行循环体,再判断循环条件。

分别使用 while、do-while、for 循环输出 10 以内所有奇数。

public class Test {
    public static void main(String[] args) {
        //while循环
//        int num = 0;
//        while(num <= 10){
//            if(num%2!=0){
//                System.out.println(num);
//            }
//            num++;
//        }

        //do-while循环
//        int num = 0;
//        do{
//            if(num%2!=0)System.out.println(num);
//            num++;
//        }while (num <= 10);

        //for循环
        for (int num = 0;num<=10;num++){
            if(num%2!=0) System.out.println(num);
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM