What is the difference of While and Do While?

0

I wanted to know if you can give me a basic definition (I'm new to this, that's why I ask for a simple explanation: /) and not so complex of the while and do, especially of the while I have more doubts because I do not understand what it is what will be executed once.

    
asked by computer96 05.10.2018 в 22:25
source

2 answers

5

While and Do While are loops, their content "may" run repeatedly, depending on a condition.

Using the structure while only happens to execute its content if a condition is checked what can happen 0, 1 or more times. Do While works in a similar way, only that we make sure that the content is executed at least once, that is, even if its condition is not fulfilled, its content is executed.

These structures are presented in the following way:

// while
while (expression) {
     // statements
}

// do-while
do {
     // statements
} while (expression);

where expression is the condition to evaluate to enter or not to execute the content of the loop, which happens yes or yes, at least once for the do while .

    
answered by 05.10.2018 / 22:46
source
2

Basically in one the verification is executed, while the other executes the code inside it and then the verification. A simple example

  public class MyClass {
        public static void main(String args[]) {
            boolean x = true;
            int c = 9;
            do{

                c++;
                x = c==10;

            } while (!x );
            System.out.println("do while: "+c);
            // Si suma por lo menos 1
            c = 9;
            x = true;

            while( !x ) {
                c++;
                x = c==10;

            };
            // No entra al ciclo por que primero comprueba. 
            System.out.println("while "+c);


        }
    }
    
answered by 05.10.2018 в 22:36