Intro to Java while loops pseudocode A Loop

  • Slides: 8
Download presentation
Intro to Java while loops pseudocode

Intro to Java while loops pseudocode

A “Loop” n n A simple but powerful mechanism for “making lots of things

A “Loop” n n 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. n Run an application until user hits “quit” button n Read characters until end of file reached n Deal card hands until game over Java has 3 loop statements: while, do, for 1

Syntax of the while statement while (condition) statement n n n condition is a

Syntax of the while statement while (condition) statement n n n 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) 2

A while Loop to Print Numbers // Print the numbers 1 thru 10 int

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; } 3

An Infinite Loop // Faulty attempt to print 1 thru 10 int x =

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

More Infinite Loops // Some infinte loops are intentional while (true){ statement(s) } //

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 } 5

Pseudocode and Loops Pseudocode is an informal, english-like, code-like way Of sketching out what

Pseudocode and Loops Pseudocode is an informal, english-like, code-like way Of sketching out what you want your code to do. 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 6

A while Loop for Powers of 2 // Computes 2^ pow. Assumes pow >=

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); 7