Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)

Similar presentations


Presentation on theme: "CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)"— Presentation transcript:

1 CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)

2 What is a Loop? A structure that will execute a line or block of code a number of (i.e., zero to many) times based on predetermined criteria Also called iteration or repetition

3 LOOPS All languages need an iteration statement Recall that Bohm and Jacopini stated that all computer solvable problems need only three types of structures: Sequence Selection Iteration (loop)

4 Loops in Java Purpose of a loop is to execute a group of lines (1 or more) a number of (0 to many) times A block gets repeated recall that a block is 1 or more simple Java statements if more than 1 line, surrounded by curly braces also called a compound Java statement a block can contain any number or type of statements block can also contain conditional logic, or other loops

5 Loops Can Have: Initialization Test to exit the loop Statements in the body of the loop Increment or other statement that will change the value that determines whether you will stay in the loop Some loops omit some of these The order of these may vary

6 Statements that Build Loops in Java Three (or is that 2?) statement types for while do... while

7 Under What Conditions Do You Use Each? forwhen you want to initialize a variable at the beginning of the loop and increment or change it after each iteration whilewhen initialization and/or increments are not done by the loop do … whilesame as while but used when you want to execute the body of the loop at least once. This is the "test after" loop

8 Structure of the "for" loop for (init-expr; bool-expr; increment-expr) statement-1 where statement-1 could be simple or compound Examples: for (int count = 1; count < 5; count = count + 1) amount = amount + payroll [count] ; for (int count = 1; count < 5; ++count) //shortcut { total = total + sale [count]; } // block could contain multiple lines

9 Structure of "for" Statement Structure: for (initialization-expression; boolean-expression; increment-expression) Example: for (counter = 1; counter < 50; counter = counter + 1) Explanation: initializationcounter = 1 //or int counter = 1 establishes the control variable, in this case, counter boolean-expressioncounter < 50 specifies the test for staying in the loop increment-expressioncounter = counter + 1 specifies the amount by which the control variable (i.e., counter) will be changed after each pass through the body of the loop

10 "for" Statement Structure - 2 "for" is lower case the three parameters are surrounded by parentheses the three parameters are separated by semi-colons need to provide space for all three parameters to be identified (some could be empty e.g., ; ;) no punctuation follows the closing parenthesis i.e., no ; (no semicolon)

11 "for" Loop Execution Steps Initialization Test Body of Loop ------------ Increment Test Body of Loop ------------ Increment Test …. continues until boolean in Test step evaluates to false; then goes to statement after the loop

12 Examples of "for" Loops for ( int count = 0; count < 10 ; count ++) System.out.println (count); for ( int count = 0; count < 10 ; count ++) { System.out.println ("iteration # = " + count); System.out.println (Math.sqrt(count)); }

13 Missing "for" Parameters int i = 0; // initialization for ( ; i<10 ; ) // both ; still there { i++; // incrementing System.out.println(i); } // hardly ever do it this way

14 "for" Loop Practice Write a for statement that makes the control variable counter start at one and take each of the values 1, 2, … up to 100 Add an action statement to the loop that will add up these numbers (total of 1 through 100) Modify the loop to add up the even numbers between 1 and 100 (2+4+6 etc.)

15 Structure of a "while" Loop while (boolean-expression) statement-1 where statement-1 can be: simple (one statement followed by semicolon) compound (multiple statements inside curly braces)

16 Structure of the "while" Statement while ( count < 3 ) while starts with a lower case letter the boolean expression is enclosed in parentheses and can be simple or complex NO punctuation following the closing parenthesis ( no ; in this "line")

17 "while" with No Block basic while (without a block) int stopAt = [user input]; int count = 1; while ( count <= stopAt ) count++; note: count ++ means count = count + 1

18 "while" with a Block while with a block int count = 0; while ( count < stopAt ) { count ++; System.out. println("count = " + count); }

19 while Practice Write code and a while statement that makes a variable start at one and take each of the values 1, 2, … up to 100 Add an action statement to the loop that will add up these numbers (total of 1 through 100) Modify the loop to add up the numbers between 1 and 100 that are divisible by 3 (3+6+9 etc.)

20 "do … while" Loop "do … while" loop has the test at the end Example: do {… //statements in body of loop answer = JOptionPane.showInputDialog("More?"); } while (answer.charAt(0).toUpperCase() == 'Y'); Note: remember to put ; after while test

21 When Do You Use a "do … while" Loop? Very useful when need to ask the question at the end of the loop You use this when you know you want to execute the body of the loop at least once Examples: Do you want to enter another customer? (after processing 1 st customer) Keep adding items while total/result is less than what you need (keep pumping gas as long as tank is not full)

22 "do... while" Practice Write a do... while loop that will read in an integer value using JOptionPane, and verify that it is between 1 and 9 If value is not between 1-9, prompt the user to enter the value, with word "again" added to the prompt text Note: an example of JOptionPane syntax is on previous slide

23 Comparing "for" and "while" Statements for (init-expr-1; bool-expr-1; incr-expr-1) { statement-1 } becomes init-expr-1; while (bool-expr-1) { statement-1 incr-expr-1 } Which is better? When? Why?

24 Avoid "Infinite Loops" Make sure that the test will eventually stop its loop the value that the boolean expression tests must eventually get to a stopping point if the test never stops the loop, the computer will "lock up" and not do anything else use "break" ([Ctrl] C in DOS window) to halt program if it won't end

25 Summary Java has selection and iteration statements similar to most computer languages Java's selection and iteration statements are much like C++ There are several types of iteration statements for different circumstances Java iteration statements can use either simple statements or blocks -- but blocks (have { }) are much less likely to be misunderstood Writing loops gets easier with practice


Download ppt "CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)"

Similar presentations


Ads by Google