The difference and usage of while and do...while

While

while(condition){
    
    
    //do your job
}

do…while

 do{
    
    
    //do your job
 }while(condition);

the difference:
do-whileStatement inleastWill loop once, butwhileAs long as the condition is not satisfied, the internal statement will not be executed

Give an example of while:

public static void testWhile() {
    
    
    int i = 10;
    while (i > 10) {
    
    
        System.out.print(i + " ");
        i--;
    }
}
上面这段代码没有任何输出,证明只要condition不满足不会执行内部语句

Give an example of do...while:

int i = 1; int sum = 0;
do {
    
    
   sum += i++; //等于 sum=sum+i;i=i+1;
} while(i <= 10);
System.out.printf("%d, %d\n", i, sum);
输出:i=11 sum=55

Give an example of do...while:

 public static void testDoWhile() {
    
    
    int i = 10;
    do {
    
    
        System.out.print(i + " ");
        i--;
    } while (i > 10);
}
输出:10
上面的输出证明虽然condition不满足但是do-while内部语句还是执行了一次

Guess you like

Origin blog.csdn.net/weixin_43814775/article/details/105983713