do-while and while comparison

后端 未结 4 1985
情话喂你
情话喂你 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:51

    The difference between a do-while and a while is when the comparison is done. With a do-while, you'll compare at the end and hence do at least one iteration.

    Equivalent code for your example

    do
    { 
        i++; 
        ++j;
        System.out.println( i * j );
    
    }
    while ((i < 10) && (j*j != 25));
    

    is equivalent to:

    i++; 
    ++j;
    System.out.println( i * j );
    while ((i < 10) && (j*j != 25)) {
        i++; 
        ++j;
        System.out.println( i * j );
    }
    

    General comprehension

    A do-while loop is an exit controlled loop which means that it exits at the end. A while loop is an entry controlled loop which means that the condition is tested at the beginning and as a consequence, the code inside the loop might not even be executed.

    do {
        
    } while ();
    

    is equivalent to:

    
    while () {
        
    };
    

    Use case

    A typical use case for a do-while is the following: you ask the user something and you want do repeat the operation while the input is not correct.

    do {
       // Ask something
    } while (input is not correct);
    

    In that case, you want to ask at least once and it's usually more elegant than using a while which would require either to duplicate code, or to add an extra condition or setting an arbitrary value to force entering the loop the first time.

    At the opposite, while loops are much more commons and can easily replace a do-while (not all languages have both loops).

提交回复
热议问题