Presentation is loading. Please wait.

Presentation is loading. Please wait.

The for Loop Syntax: for ( expression1 ; condition ; expression2 ) statement ; for ( expression1 ; condition ; expression2 ) { statement ; } Same as: expression1.

Similar presentations


Presentation on theme: "The for Loop Syntax: for ( expression1 ; condition ; expression2 ) statement ; for ( expression1 ; condition ; expression2 ) { statement ; } Same as: expression1."— Presentation transcript:

1 The for Loop Syntax: for ( expression1 ; condition ; expression2 ) statement ; for ( expression1 ; condition ; expression2 ) { statement ; } Same as: expression1 ; while ( condition ) { statement ; expression2 ; }

2 Example for Loop int numEmployees,curNum; System.out.print(“Enter Number of Employees: “); numEmployees = scan.nextInt(); if (numEmployees > 0) { for (curNum = 0; curNum < numEmployees;curNum++) { System.out.println( “Welcome to CorpLand!” ); }

3 Looping for Input char letterEntered = ‘A’; String stringE; while (letterEntered != ‘Z’) { System.out.print(“Enter a letter: “); stringE = scan.next(); letterEntered = stringE.charAt(0); }

4 Looping until Flag boolean noMoreData(); boolean done = false; … while (!done) { … // do a bunch of stuff … if (noMoreData() == true) done = true; } System.out.println(“ We’re all through – thank you!”);

5 Nested Loops int i, j ; for (i=0; i < 10; i++) { for (j=0; j < 10; j++) { System.out.print(i); System.out.print(j); System.out.print(“ “ ); } System.out.println(); }

6 The do-while Loop Syntax do statement ; while (condition); do { statement ; } while (condition);

7 do-while Example char letterEntered; String stringE; do { System.out.print(“Enter a letter: “); stringE = scan.next(); letterEntered = stringE.charAt(0); } while (letterEntered != ‘Z’);

8 What Is This? while (!stringEntered.equals(“apple”)) { System.out.println( “Enter a red fruit: “); stringEntered = scan.next(); } while (!stringEntered.equals(“banana”)) { System.out.println(“Enter a yellow fruit: “); stringEntered = scan.next(); } while (!stringEntered.equals(“pomegranate”)) { System.out.println(“Enter a random fruit: “); stringEntered = scan.next(); }

9 What Is This? for (i = 0; i < 10 ; i++) System.out.println( “Interesting, isn’t it?”); while (answer.charAt(0) != ‘D’) { System.out.print( “Enter an answer: “); answer = scan.next(); } while (answer.charAt(0) != ‘D’) { System.out.print( “Enter an answer: “); answer = scan.next(); }

10 What Is This? void kingsChair(int loopCounter) { int num; for(num = 0; num < loopCounter; num++) System.out.println(“AAAAAAAAAAAAAAAAAAAAAAAAAA”); }


Download ppt "The for Loop Syntax: for ( expression1 ; condition ; expression2 ) statement ; for ( expression1 ; condition ; expression2 ) { statement ; } Same as: expression1."

Similar presentations


Ads by Google