Class Notes for While Loops |
|
// While Loops - are event or condition controlled loops
// BUT can also be designed as count controlled
// Always make sure you provide a way for the while loop
// to exit inside the loop; otherwise you will create
// an infinite loop (which is bad [usually]).
// This is a while loop designed to be a count controlled loop
// We know how many times this loop will run (10).
// while ( THIS CONDITION IN HERE IS TRUE) { LOOP THIS }
int i = 0;
while (i<10){
i++;
System.out.print(i+" ");
}
System.out.println();
// This is a while loop designed as an event controlled loop
// The loop will exit if the user inputs anything less then 0
Scanner keyboard = new Scanner(System.in);
int j = 0;
int sum = 0;
while (j >= 0){
System.out.print("Type in an integer to add to "+sum+" (-1 to EXIT): ");
j = keyboard.nextInt();
if(j >= 0){
sum += j;
}
}
System.out.println("Your Sum is: " + sum);
// The Do While loop is the same as a while loop, but it is
// guaranteed to run at least once; the condition is checked
// after the loop is run NOT before it.
int k = 0;
do{
System.out.print(k+" ");
k--;
} while(k>0);
System.out.println();
Videos |
|