import java.util.Scanner; // Examples of how Iteration works in Java // Ferworn Fall 02 updated Fall 05 public class Iteration { public static void main(String[] args) { Scanner Keyboard = new Scanner(System.in); int num = 10, other = 10; // Demo 1: a simple while loop System.out.println("***Demo 1"); System.out.println("num is: " + num); while(num > 0) num--; System.out.println("num is: " + num); // Demo 2: a while loop with a block System.out.println("***Demo 2"); while(num < 10) { num++; System.out.println(num); } // Demo 3: forcing correct input using while // (0 or more times iteration) System.out.println("***Demo 3"); num = 1; while(num != 0) { System.out.println("Please enter the number 0"); num = Keyboard.nextInt(); } //Demo 4: a simple do while loop //Used where you need to perform the body of the loop //at least once and possibly more times. System.out.println("***Demo 4"); num = 5; do { System.out.println ("This code will be executed at least once"); num = 0; }while(num != 0); //Demo 5: forcing correct input using //do while (An example of "Mall Rat code" System.out.println("***Demo 5"); do { System.out.println("Please enter the number 0"); num = Keyboard.nextInt(); }while(num != 0); //Demo 5A: forcing correct input using do while //(more than 1 choice) System.out.println("***Demo 5A"); do { System.out.println ("Please enter the number 0,1 or 2"); num = Keyboard.nextInt(); }while((num != 0) && (num != 1) && (num != 2));; //Demo 6: Nesting loops (count up to 39..weirdly) System.out.println("***Demo 6"); String numstring = new String(); num = 0; other = 0; while(num <= 3) { while(other <= 9) { numstring = "" + num + "" + other; System.out.println(numstring); other++; } other = 0; num++; } //Demo 7: simple for loop (use "for" when //you know how many times through) System.out.println("***Demo 7"); for(num=0;num<10;num++) System.out.println(num); //Demo 8: nested for loop replicating Demo 6. System.out.println("***Demo 8"); for(num=0;num<=3;num++) for(other=0;other<10;other++) { numstring = "" + num + "" + other; System.out.println(numstring); } //Demo 9: more about break. System.out.println("***Demo 9"); while(true) break; //Demo 10: exercise. given "rows" and "columns" //print a "block" of //asterisks (*). //For example if rows=3 and columns=4 then //**** //**** //**** System.out.println("***Demo 10"); //Easy way! System.out.println("****"); System.out.println("****"); System.out.println("****"); //More general way for(int i=0;i<3;i++) { for(int j=0;j<4;j++) System.out.print("*"); System.out.println(); } } }