For and While Loops Name___________________________ /** * Simple "for loop" examples */ int x; for(x=1; x<11; x=x+1) { System.out.println("Count is: " + x); } System.out.println("The value of x after the loop is: " + x); for(int i=1; i<11; i++) { System.out.println("Count is: " + i); } System.out.println("The value of i after the loop is: " + i); /** * Basic nested loop */ for(int x=1; x<5; x++) { System.out.print(x + " ("); for (int y=1; y<=3; y++) { System.out.print(y); } System.out.println(")"); } /** * Here's how they mess with you */ for(int i=1; i<=5; i++) { for (int j=1; j<i; j++) System.out.print("-"); for (int k=i; k<=5; k++) System.out.print("|"); System.out.println(""); } /** * A simple "while loop" example. */ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } Examples of break and continue and other unstructured bad ideas /** * You are "allowed" to change the loop control variable * inside the loop, but please DON'T */ for(int z=1; z<11; z++) { z = z + 2; // Don't do this!!! System.out.println("Count is: " + z); } /** * If the keyword break is executed inside a for-loop, the loop is immediately * exited (regardless of the control statement). Execution continues with * the statement immediately following the closing brace of the for-loop. */ for (int y=1; y<3; y++) for (int count = 1; count <= 10; count++) { if (count == 6) { break; // Don't do this!!! Not part of the AP subset } System.out.println(count); } /** * If continue is encountered inside any loop, all remaining code in the loop * is skipped for this particular iteration; however, looping continues in * accordance with the control expression. */ for (int count = 1; count <= 10; count++) { if (count == 6) { continue; // Don't do this!!! Not part of the AP subset } System.out.println(count); }