While loop repeats the set of code when the condition you set is true. The condition you set for the loop must be a Boolean expression. A Boolean expression can only take a true or false value. Hence, you will expect that the while loop will not be executed in the case when the condition for the loop is false.
Before I proceed to explain further on while loop, let's look at one example to visualize how do we construct the while loop in Java.
For the above example, I wrote a simple program which uses the while loop to do a little count down and eventually print the string "Blast off!" after the count down is done. Since we normally count down based on integer value, we will set our controlling variable in this case to be an integer. For simplification purposes, we will start counting down from 10. You may want to count down from 100 if you like, it will work as well. So we assign the integer value 10 to our controlling variable.
The general format of the while loop would look some thing like this: while(condition){ //codes to repeat}. In the above case, the condition I want the loop to carry on executing the code will be when the value of x is more than zero. It does not make any sense to blast off at other integer values. Hence, as long as the value of x is more than zero, the codes inside the while statement will carry on executing until the value of x reaches zero.
One question? Do you know why the value of x will reach zero in this case? The reason behind this is that because we add the code "x--;" inside the while loop. So every time the loop runs, it will first print out the value of x, after that it will decrease the value of x by one. Hence, our code will eventually terminates. We would not like a never ending loop as it will not yield the results we are expecting to get.
So try running the above code and you will get the following result:
As we expected, our program indeed print out the values of x when each loop runs, until the value of x reaches 0. This is when the condition for the while loop is false and the loop stops executing. Our program would moves on to the last line of our code and print out "Blast off!!" and end our little simple program to illustrate the function of while loop.
Apart from basic count down, if you would not want to show the integers in this case, you may do a slight change to the program and do some thing like this:
So, if we try running the program, we will get some thing like this:
There are various ways you may use the while loops for your program. Try exploring and practice different ways in which you can use this loops. Who knows, one day it might prove useful to you.
This marks the end of the while loop tutorial, I will be uploading tutorial for other type of loops soon. So stay tuned.
No comments:
Post a Comment