Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Java while loops pseudocode. 1 A “Loop” A simple but powerful mechanism for “making lots of things happen!” Performs a statement (or block) over.

Similar presentations


Presentation on theme: "Intro to Java while loops pseudocode. 1 A “Loop” A simple but powerful mechanism for “making lots of things happen!” Performs a statement (or block) over."— Presentation transcript:

1 Intro to Java while loops pseudocode

2 1 A “Loop” A simple but powerful mechanism for “making lots of things happen!” Performs a statement (or block) over & over Usually set up to repeat an action until some condition is satisfied, e.g. Run an application until user hits “quit” button Read characters until end of file reached Deal card hands until game over Java has 3 loop statements: while, do, for

3 2 Syntax of the while statement condition is a true/false (boolean) expression statement is a single or block statement If condition is initially false, the statement is never executed If the condition is true, the statement is executed. Repeat this step. The statement should eventually make the loop stop (unless you want to have an infinite loop) while (condition) statement

4 3 A while Loop to Print Numbers // Print the numbers 1 thru 10 int x = 1; while (x <= 10){ System.out.println(x); x = x + 1; }

5 4 An Infinite Loop // Faulty attempt to print 1 thru 10 int x = 1; while (x <= 10){ System.out.println(x); }

6 5 More Infinite Loops // Some infinte loops are intentional while (true){ statement(s) } // Others are not int x = 5; while (x < 10){ statement(s) which don’t change x }

7 6 Pseudocode and Loops initialize game while( the game isn’t over){ process player input process bots update game state determine if game should end } if game should be saved save game quit Pseudocode is an informal, english-like, code-like way Of sketching out what you want your code to do.

8 7 A while Loop for Powers of 2 // Computes 2^ pow. Assumes pow >= 0. int result = 1; while (pow > 0){ result = result * 2; pow = pow - 1; } System.out.println(“result is “ + result);


Download ppt "Intro to Java while loops pseudocode. 1 A “Loop” A simple but powerful mechanism for “making lots of things happen!” Performs a statement (or block) over."

Similar presentations


Ads by Google