SEARCH W7R

Sunday, April 08, 2012

Java Basics: The While Loop

The while loop is the simplest of the loop syntax available to you as a Java programmer. The general idea is if a condition is true, then repeat til it is false. The only additional detail to make the idea complete is that the condition is checked before and after every loop.

Source


Specific Examples!
1. Condition is Never True Case
int count = 10;
while(false){
   count--;
   System.out.println("Inside the loop");
   //this area (inside the semi colons) will never be executed
}
System.out.println("After the while loop");
System.out.println("count: "+count);

2. Condition is Always True (Infinite Loop)

int count=0;
while(true){
   count++;
   System.out.println("Inside the loop. Looped "+count+" times.");
   //executed infinitely many times WARNING: could harm computer if not terminated
}
System.out.println("After the while loop");

3. Counting Up To A Certain Number
int topNumber=900;
int lowNumber=0;
while(lowNumber<topNumber){
   lowNumber++;
}
System.out.println("final value for lowNumber is "+lowNumber);

4. Count Down To A Certain Number

int topNumber=900;
int lowNumber=0;
while(lowNumber<topNumber){
   topNumber--;
}
System.out.println("final value for lowNumber is "+lowNumber);

No comments: