Java Loops

While Loop:

int myCount = 0; while (myCount < 4) { // Add code here to be repeated myCount++; }

- The code within the brackets will be repeated until the specified condition is met

- The condition doesn't have to be a count, it could loop until user input is valid or some other useful condition

- Be sure to make a condition that will be reached, otherwise it will continue running until it causes problems

- If you get stuck in an infinite loop (unending loop), use the emergency stop button (red square) in your IDE (e.g. Eclipse/NetBeans)

For Loop:

for (int i = 0; i < 4; i++) { // Add code here to be repeated }

- This is a shorter way to make a loop that loops a counted number of times like the "while" example above

Traditional Loop Through Arrays:

int [] myIntArray = {7,3,6,3,1,2}; for (int i = 0; i < myIntArray.length; i++) { System.out.println( myIntArray[i] ); }

- Below is a simpler method, but this method is useful if you want to acess the index number or if you want to access only some of the values in an array by adjusting the start index or conditional

For-Each Loop (Simplified Array Loop):

int [] myIntArray = {7,3,6,3,1,2}; for (int myInt : myIntArray) { System.out.println( myInt ); }

- For each cycle of this loop, the temporary variable "myInt" will take on the value of a different number in the array

Challenge

Create a loop that displays every multiple of 12 up to the 50th;

Quiz

Completed