while loop with break and continue

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

The code block is executed only if the condition is true

Example 1

   int i=0;	
    while( i < 5) {
    	 System.out.println(i);
    	 i=i+1;
    }
Output
0
1
2
3
4
In above code we are first printing the value of the variable and then incrementing the value of variable by 1. So the output prints 0 to 4 and not 0 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;
		
    while( my_condition ) {
    	 System.out.println(my_condition);
    	 my_condition=false;
    }
Output is
true

Infinite loop

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

What will happen if the condition is false always ?

The code block will never execute.

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

while loop with break and continue

Break and continue in 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;	
	    while( i < 5) {
	    	 i=i+1;
	    	if(i==2) {
	    		break;
	    	}
	    	 System.out.println(i);
	    	
	    }
Output is here
1
After printing 1 ( first 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.
	    while( i < 5) {
	    	 i=i+1;
	    	if(i==2) {
	    		continue;
	    	}
	    	 System.out.println(i);
	    	
	    }
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 be starting of the loop without executing 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