简体   繁体   中英

While and do while loops

I'm new to this site and also very new to Java and I'm trying to understand the do while loops

Question: What is the output and why?

public class DoWhile {
    public static void main(String[] args) {
        int i = 1; 

        do { 
            System.out.println("i is : " + i); 
            i++; 
        } while(i < 1);  
    } 
} 

I get that the output is "i is : 1" but I'm trying to understand why. It stops once it hits while because i isn't less that 1, right?

Just trying to get my head around it so any help will be appreciated.

Yes. Correct.

do { } while (condition);

This will perform the code at least once, regardless of the condition. After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop.

Yes, the output is

i is : 1

The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; it's only evaluated at the end of each iteration. This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration.

i is 1 at the start, then print occurs, then i is incremented to 2 . Then the condition is evaluated -- it's false , so the loop terminates.

输出仅为1因为do导致循环至少执行一次,但是while中的条件不会让循环重复执行,因为i永远不会小于1

It is no more 1

public class DoWhile {
    public static void main(String[] args) {
        int i = 1; // i is 1

        do { 
            System.out.println("i is : " + i); //still i is 1
            i++; // this makes i = 2;
        } while(i < 1);  
    } 
} 

if you notice the comments it is no more 1 after the first iteration

Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once.

After the do block is executed the i value becomes 2 and the while block is not executed.

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM