do-while and while comparison

后端 未结 4 1942
情话喂你
情话喂你 2021-01-05 20:09

do-while:

do
{ 
    i++; 
    ++j;
    System.out.println( i * j );

}
while ((i < 10) && (j*j != 25));

I am learning about do-w

4条回答
  •  礼貌的吻别
    2021-01-05 20:56

    No, the two codes are not equivalent. do-while only checks the condition at the end of the loop so i++, ++j and System.out.println(i * j) happen at least once regardless of the initial values of i and j. while skips the entire loop if the condition isn't true for the first time the loop is entered.

    You can achieve the same effect with while by copying the loop's body once before the loop, for instance.

提交回复
热议问题