Wednesday, October 5, 2016

Muhammad Akbar

While Loop in Java-Tutorial

The while loop contineously executes a block of statements while a particular condition is true

The structure of while loop is:
While(condition)
{
 // do something
}
Meaning of this above piece of code is: As long as the condition mentioned in the while loop holds true, the //do something part will execute. Whenever the condition becomes false, the loop will break and the control goes to the next statement after the loop.
Example
public class WhileDemo {

 // we want to print 10 to 1 backwards
 public static void main(String[] args) {
  int i = 10; // initiate the count
  
  while (i > 0) { // while checks if i is greater than 0
   System.out.print(i + " ");
   i--; // decrease the value of i by 1
  }
 }
}
Try It
The above program prints:
10 9 8 7 6 5 4 3 2 1
Why did we put i-- statement inside the while loop? What could have happened otherwise?
We need to remember that we used the condition “when I is greater than ZERO” and we initiated I with 10. SO, if we don’t put a decrement of i inside the loop, the value of i will never be changed and this can cause an infinite loop and ultimately a shutdown of JVM due to low memory space.
So, while writing the while, we must be careful that it shouldn’t create an infinite loop.

        

  Do While Loop in Java

Muhammad Akbar

About Muhammad Akbar -

Author Description here.. Nulla sagittis convallis. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.

Subscribe to this Blog via Email :

Hello Every One thanks For Visit My site You Can Suggest any Idea About site And Related Education Information Provide me Its Best Content For you am Include in this Site And feel free contact And email now I hope This site very help full you