/** * Name: Erica Eddy * Course: CSCI 241 - Computer Science I * Section: 001 or 002 * Assignment: 1 * * This example shows how results can differ greatly if a loop is nested * inside another. 'for' loops are used here, but an equivalent while loop * could be substituted with identical results. */ public class NestedFor { public static void main (String [] args) { // separate loops // this version has no connection between the loops //int i; // first, run the 'i' loop completely from start to finish for (int i = 0; i < 5; i++) { System.out.print("-"); } // next, run through the 'j' loop completely from start to finish for (int j = 0; j < 5; j++) { System.out.print("@"); } // end the current line System.out.println(); // nested loops, version 1 // this version runs through a complete the 'j' loop every time you // get a new value for i // So, you'll get a lot more '@' signs printed than '-' symbols for (int i = 0; i < 5; i++) { System.out.print("-"); // every time you get a new value for i, do entire 'j' loop for (int j = 0; j < 5; j++) { System.out.print("@"); } // end inner for loop } // end outer for loop // end the current line System.out.println(); // nested loops, version 2 // this version does the 'j' loop every time you get a new value for i, // but j's initial value depends on i // This means that the number of iterations in the 'j' loops gets // reduced by one each time i changes, because j gets its initial value // from the current value of i. for (int i = 0; i < 5; i++) { System.out.print("-"); for (int j = i; j < 5; j++) { System.out.print("@"); } // end inner for loop } // end outer for loop } }