do while loop with break and continue

Syntax of do while loop
do {
	// code block to execute
}while ( condition)
condition : Check the logic and it should return true or false.

The first iteration is done and code block is executed once irrespective of outcome of condition ( true or false ) , after this the condition is checked. Based on the outcome of condition check further continuation of loop is decided.

Example 1

int i=0;	
	do {
	  i=i+1;
	  System.out.println(i);
	}while (i<5);
Output
1
2
3
4
5
In above code we are first incrementing the value of the variable by 1 and then printing the value of variable. So the output prints 1 to 5.

Understanding condition

In place of using integer variable and incrementing , we will use one Boolean variable with initial value set to true. Inside the loop we will set the value of the variable to false. As expected the loop will execute once only.
   boolean my_condition=true;
	do{
	    	 System.out.println(my_condition);
	    	 my_condition=false;
	  }while ( my_condition==true);
Output is
true

Infinite loop

What happens if the condition never became false. We will create one infinite loop.
  int i=0;	
	do {
	  	 i=i+1;
	   	 System.out.println(i);
	}while (i >-5);

What will happen if the condition is false always ?

The code block will execute once.

This is the main difference between do while loop and while loop.

do while loop with break and continue

Break and continue in do while loop
Inside the loop of we use break; satement then the execution will come out of the loop.

Example using break

	int i=0;	
	do {
	  	 i=i+1;
	  	 if(i==2) {
	  		 break;
	  	 }
	   	 System.out.println(i);
	}while (i < 5);
Output is here
1
After printing 1 ( first iteration ), in second iteration i value will be equal to 2, so the break statement will be encountered and the execution will come out of the loop.

Example using continue

In above code we will replace break with continue.
	    	int i=0;	
	do {
	  	 i=i+1;
	  	 if(i==2) {
	  		 continue;
	  	 }
	   	 System.out.println(i);
	}while (i < 5);
Output is here
1
3
4
5
Except printing 2 , all values from 1 to 5 will be printed. When i value became 2, the continue statement is encountered and execution returns to the starting of the loop without executing balance ( print ) command.

Difference between break and continue

The execution stops and comes out of the loop once break statement is encountered. In case of continue, further execution of the code block is stopped and loop continues from starting of the loop.

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer