user3063828
user3063828

Reputation: 3

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.

Upvotes: 0

Views: 300

Answers (5)

Sandy
Sandy

Reputation: 226

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

Upvotes: 0

Hessam
Hessam

Reputation: 1415

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

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208964

The output is just 1 becuase the do causes the loop to execute at least once, but the condition in the while doesn't aloow the loop to reiterate, because i is never less than 1

Upvotes: 0

rgettman
rgettman

Reputation: 178253

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.

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

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.

Upvotes: 1

Related Questions