3-3 Loops - Ex: do{ x=input }while (x<3 || x>7)...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Computer Science 3/3/08: Loops for ((initial);(test in Boolean);(increment)) { } Ex: for (int i=1;i<50;i++){ } (When i=50 you will jump out of the loop to the next command) If you put a true for the test, you will loop forever. Therefore, you have to put something there that changes. You could write a loop like this but then you would need a break to get out: for( ; ; ){} int i=1 while ([Boolean expression]){ i=i+1 } (as long as Boolean expression is true you keep looping, when it is false you jump down to next statement) Ex: x=input While (x<3 || x>7){ x=input; } Proceed with program (NOTE: x=input is shorthand note but means using the JOptionPane stuff to get an input value.) (This loop is called an input loop and is also a Pretest loop because it tests before it does anything) Post Test Loop do { } while ([Boolean expression]); (Only do the Boolean expression section once)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Ex: do{ x=input }while (x<3 || x>7) Pretest Loops are strongly recommended. Post Test loops are rarely used. Ex: A Fibonacci series Looping Programming public static void Fib(int n){ int prev=0; int next=1; for (int i=0; i<=n; i++){ System.out.println(prev); next=next+prev; prev=next-prev; } } Hints for Drunkard Problem: Check whether you are outside the circle every step Sqrt(x^2+y^2)<r Three loops The hundred trials The taking steps The different distances In English what you are doing: Loop 1: take a step in a random direction Record new location Check whether new location is outside of radius Loop 2: run loop 1 until outside radius 100 times Record average of how many steps Loop 3: Change radius and redo loops 2 and 1 Every method can be static....
View Full Document

This note was uploaded on 04/27/2008 for the course CMPT 241 taught by Professor Shields during the Spring '08 term at Simons Rock.

Page1 / 2

3-3 Loops - Ex: do{ x=input }while (x<3 || x>7)...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online