Friday, January 25, 2013

The While Loop


The while loop and for loop may overlap at times because they have a similar function. For a beginner, it may not be quite obvious when to use one and not the other. The basic difference of the two loops though is that;
  1. Use the while loop if you do not know how many times you need to loop
  2. Use the for loop if you actually know how many times you will need to go through the loop
The canonical form of the while loop
while(condition) {
    statement 1;
    statement 2;
    statement n;
}
The condition is either a literal (the keywords true or false) or an expression that will evaluate to either true or false (boolean values).
The basic ideas in the while loop are the following.
  1. The condition is evaluated for the first time, if the condition is true or resolves to true, then;
  2. Perform statement 1, then;
  3. Perform statement 2, then;
  4. Perform statement n, then;
  5. The program detects that we are at the end of while block (the closing curly brace is the end of the while block)
  6. The program will loop back to the condition and re-evaluate it again, if it still true, then;
  7. Perform statement (again)
  8. rinse repeat until you get the end of the end of the block again and until you get to re-evaluate the condition (again).
You will only drop off end of the while block if and when the condition evaluates to false. This is the reason it is best to remember that you need write code inside the while block that will make the condition false at some point in time, lest you end up in a perpetual loop.
Example code:
    import static java.lang.System.out;

    class While {

        public static void main (String [] args){
    
            boolean condition = true;
            int counter = 0;

            while(condition) {
                out.println(counter);
                counter = counter + 1;
                if(counter >10) {
                    condition = false;
                }
            }
        }
    }
Like the if statement, you can also nest a while loop inside another while loop.


Call me and you will get the knowledge and skills you need instantly.

For inquiries contact me on my mobile number or email me at inquiry@eglobiotraining.com. View my multiply site http://erwinglobio.multiply.com
Prof. Erwin M. Globio, MSIT
Senior IT Lecturer
Far Eastern University
Email Address: inquiry@eglobiotraining.com
Skype: erwinglobio
Call Now:
SMART: 09393741359
SUN: 09323956678



No comments:

Post a Comment