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