Thursday, October 31, 2013

Flow Control - while loop

Iteration Statements

java's iteration statements are for,while and do - while.These statements create what we commonly call as loops, As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. As you will see, Has a loop to fit any programming need.

while loop

The while loop is java's most fundamental loop statement. it repeats a statement or block while it controlling expression is true. Here is its general from;
while (condition) {
         // body of loop
}
The condition can be any boolean expression, The body of the loop will be executed as long as the conditional expression is true, When condition become false, control passes to the next line of code immediately following the loop, the curly braces are unnecessary if only a single statement is being repeated.

Here is a while loop that counts down from 10, print exactly ten line of "tick"
class WhileExample{
               public static void main(String args[]){
                             int i = 10;
                             while(i > 0){
                                        System.out.println("tick "+i);
                                        i--;
                             }
               }
}
Output :
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

Sine the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the the condition is false to begin with. For example, in the following fragment, the call to println() is never executed.
class WhileExample {

    public static void main(String args[]) {
        int a =10, b=20;
        while (a> b) {          
            System.out.println("not print");
        }
     
    }
}
The body of the while (or any other of java loops ) can be empty. This is because a null statement (one that consists only of a semicolon ) is syntactically valid in java.
example this program finds of the midpoint between i and j.
class WhileExample {

    public static void main(String args[]) {
       int i, j;
       i = 100;
       j = 200;
        while (++ i < --j) ;
        System.out.println("midpont is "+i);
       
    }
}
Output
               midpont is 150
Here is how this while loop works, The value of i is incremented, and the value of j is decremented, these values are then compared with one another, if the new value of i is less then the new value of j then the loop repeats, if i is equal to or greater then j stops,Upon exit form the loop i will hold a value that is midway between the original value of i and j , (Of course, this procedure only works when i is less then j to begin with.) As you can see, there is no need for a loop body, expression, itself.


No comments:

Post a Comment