cis 234: loops adapted from materials by dr. donald bell, 2000 (updated april 2007)

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

Upload: buddy-washington

Post on 02-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

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

CIS 234: LOOPS

Adapted from materials byDr. Donald Bell, 2000(updated April 2007)

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

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

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

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)

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

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

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

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

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

Statements that Build Loops in Java

Three (or is that 2?) statement types for while do ... while

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

Under What Conditions Do You Use Each?

for when you want to initialize a variable at the beginning of the loop and increment or change it after each iteration

while when initialization and/or increments are not done by the loop

do … while same as while but used when you want to execute the body of the loop at least once. This is the "test after" loop

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

Structure of the "for" loop for (init-expr; bool-expr; increment-expr)

statement-1where 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

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

Structure of "for" Statement

Structure: for (initialization-expression; boolean-expression; increment-expression)

Example: for (counter = 1; counter < 50; counter = counter + 1) Explanation:

initialization counter = 1 //or int counter = 1

establishes the control variable, in this case, counter

boolean-expression counter < 50

specifies the test for staying in the loop

increment-expression counter = 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

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

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

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

"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

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

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

}

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

Missing "for" Parameters

int i = 0; // initializationfor ( ; i<10 ; ) // both ; still there

{i++; // incrementingSystem.out.println(i);

}// hardly ever do it this way

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

"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.)

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

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)

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

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

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

"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

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

"while" with a Block

while with a blockint count = 0;while ( count < stopAt ){

count ++;System.out. println("count = " + count);

}

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

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

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

"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

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

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 1st customer) Keep adding items while total/result is

less than what you need (keep pumping gas as long as tank is not full)

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

"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 textNote: an example of JOptionPane syntax is on previous slide

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

Comparing "for" and "while" Statements

for (init-expr-1; bool-expr-1; incr-expr-1){ statement-1 }

becomesinit-expr-1;while (bool-expr-1)

{ statement-1 incr-expr-1 }

Which is better? When? Why?

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

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

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

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