// Whitaker Brand // TA: Amelia Schull // Section: BB // // This program demonstrates the basics of a for loop. The for loop // is used to execute the same code multiple times. It is done (commonly) // by using an int variable as a counter, and incrementing that variable // until it reaches some stopping point. public class ForLoopExample { public static void main(String[] args) { int x = 5; // Reminders about variable re-assignment: // We can increase x's value by 1 in three different ways. // These all do (practically) the same thing x = x + 1; x += 1; x++; // initialization, test, update // we usually start i at 1 (or 0), and we usually use i++ // what goes in the middle in the test depends on how many times you want the loop to execute for (int i = 1; i <= 4; i++) { System.out.println("Second favorite movie: Hogfather"); } System.out.println("For loop is done."); // Same thing, but spread across multiple lines. // Can be helpful to do this with the java debugger: for ( int i = 1; // initialization: set a starting value for the forloop counter i <= 4; // test: use the forloop counter to make an expression that determines how long to continue looping i++ // update: define how to update the counter between loop iterations ) { // inside these braces is the forloop body System.out.println("Second favorite movie: Hogfather"); System.out.println("Never bad to print out i for testing. i = " + i); } System.out.println("For loop is done."); } }