/** * Name: Erica Eddy * Course: CSCI 241 - Computer Science I * Section: 001 or 002 * Assignment: 1 * * This example shows how to convert a 'while' loop into a 'for' loop, * and vice versa. * Notice how the body of the 'for' loop contains one fewer statement * than the body of the 'while' loop (where did it go?) */ public class WhileFor { public static void main (String [] args) { // example of a while loop that prints the loop control variable's // value each time the loop executes int x = 5; while (x > 0) { System.out.println ("x = " + x); x--; } System.out.println("at end, x = " + x); // example of a for loop that does the same thing. // Note that the y must be declared outside of the loop, so that its // final value can be printed outside the loop. int y; for (y = 5; y > 0; y--) { System.out.println ("y = " + y); } System.out.println("at end, y = " + y); // Exercise: how would you rewrite this loop as a while loop? for (int a = 10; a > 0; a -= 2) System.out.println("a = " + a); } }