ตั้งค่าการอ่าน

ค่าเริ่มต้น

  • เลื่อนอัตโนมัติ
    Java

    ลำดับตอนที่ #6 : Java II - Loops

    • อัปเดตล่าสุด 28 ธ.ค. 61


    While Loops

    Loops

              You often need to repeat similar code in programming. For example, you might want to print numbers from 1 to 100. It's not efficient to write System.out.println() 100 times. Instead, we could use loops, also known as iteration.


    While Loops

              One of the most common types of iteration is the while loop. While loops are written like the example below. The code inside the { } gets repeated while the condition is true.


    How While Loops Work

              Let's learn the flow of while loops as shown below. First, a variable is initialized before the while loop. After each iteration of the while loop, the variable is updated and the condition is checked again. This same process is continued until the condition becomes false.


    Using While Loops

              Let's look at an example of a while loop. Below is a program in which the Ninja jumps five times. The variable is initialized outside the loop and is incremented by 1 each time the loop repeats. The condition becomes false in the sixth round, and the loop stops.


    Infinite Loops

              If you forget to add 1 to the i variable in the loop, i will not change, and the condition will always be true. This will cause an infinite loop, and put a huge load on the computer. You have to ensure that the loop is false at some point.



    For Loops

              The for loop is another type of iteration. In the (), we initialize the variable, add a condition, and update the variable. Each step is separated by semicolons ; . You can compare the two kinds of loops in the images below.


    Using For Loops

              Using a for loop, let's rewrite the code to make the Ninja jump 5 times. You can use either a for loop or a while loop to repeat the code, but a for loop often makes it simpler. Make sure to master both loops!



    Break & Continue

    Break Statements When you want to exit the loop immediately, you can use the break statement. Break statements are usually combined with if statements, like in the image below. They can be used in the same way with while loops too.


    Continue Statements

              Unlike break statements that end a loop, continue statements skip the loop for that specific iteration. Continue statements can be used in the same way with both for loops and while loops.





    ติดตามเรื่องนี้
    เก็บเข้าคอลเล็กชัน
    นิยายแฟร์ 2024

    ผู้อ่านนิยมอ่านต่อ ดูทั้งหมด

    loading
    กำลังโหลด...

    อีบุ๊ก ดูทั้งหมด

    loading
    กำลังโหลด...

    ความคิดเห็น

    ×