bcs.solano.edu

bcs.solano.edu

Chapter 6: Looping Objectives Learn about the loop structure Create while loops

Use shortcut arithmetic operators Create for loops Create dowhile loops Nest loops Improve loop performance Java Programming, Seventh Edition 2 Learning About the Loop Structure Loop A structure that allows repeated execution of a block of

statements Loop body A block of statements Executed repeatedly Iteration One execution of any loop Java Programming, Seventh Edition 3

Learning About the Loop Structure (contd.) Three types of loops while The loop-controlling Boolean expression is the first statement for A concise format in which to execute loops dowhile The loop-controlling Boolean expression is the last statement Java Programming, Seventh Edition

4 Learning About the Loop Structure (contd.) Java Programming, Seventh Edition 5 Creating while Loops while loop Executes a body of statements continually

As long as the Boolean expression that controls entry into the loop continues to be true Consists of: The keyword while Followed by a Boolean expression within parentheses Followed by the body of the loop; can be a single statement or a block of statements surrounded by curly braces Java Programming, Seventh Edition 6

Writing a Definite while Loop Definite loop Performs a task a predetermined number of times Also called a counted loop Write a definite loop Initialize the loop control variable The variable whose value determines whether loop execution continues While the loop control variable does not pass a limiting value, the program continues to execute the body of the while loop

Java Programming, Seventh Edition 7 Writing a Definite while Loop (contd.) Java Programming, Seventh Edition 8 Writing a Definite while Loop (contd.)

Write a definite loop (contd.) The body of the loop must include a statement that alters the loop control variable Infinite loop A loop that never ends Can result from a mistake in the while loop Do not write intentionally Java Programming, Seventh Edition 9

Writing a Definite while Loop (contd.) Java Programming, Seventh Edition 10 Writing a Definite while Loop (contd.) Suspect an infinite loop when: The same output is displayed repeatedly The screen remains idle for an extended period of time

To exit an infinite loop, press and hold Ctrl, then press C or Break Java Programming, Seventh Edition 11 Writing a Definite while Loop (contd.) Figure 6-4 A while loop that displays Hello twice Java Programming, Seventh Edition

12 Pitfall: Failing to Alter the Loop Control Variable Within the Loop Body Prevent the while loop from executing infinitely The named loop control variable is initialized to a starting value The loop control variable is tested in the while statement If the test expression is true, the body of the while statement takes action Alters the value of the loop control variable The test of the while statement must eventually evaluate

to false Java Programming, Seventh Edition 13 Pitfall: Failing to Alter the Loop Control Variable Within the Loop Body (contd.) Java Programming, Seventh Edition 14

Pitfall: Creating a Loop with an Empty Body Loop control variable A variable that is altered and stored with a new value loopCount = loopCount + 1 The equal sign assigns a value to the variable on the left The variable should be altered within the body of the loop Empty body A body with no statements Caused by misplaced semicolons

Java Programming, Seventh Edition 15 Pitfall: Creating a Loop with an Empty Body (contd.) Java Programming, Seventh Edition 16 Altering a Definite Loops Control Variable

Incrementing the variable Alter the value of the loop control variable by adding 1 Decrementing the variable Subtract 1 from the loop control variable Clearest and best method Start the loop control variable at 0 or 1 Increment by 1 each time through the loop Stop when the loop control variable reaches the limit Java Programming, Seventh Edition

17 Altering a Definite Loops Control Variable (contd.) Java Programming, Seventh Edition 18 Writing an Indefinite while Loop Indefinite loop Altered by user input Controlled by the user

Executed any number of times Validating data Ensure a value falls within a specified range Use indefinite loops to validate input data If a user enters incorrect data, the loop repeats Java Programming, Seventh Edition 19 Writing an Indefinite while Loop (contd.)

Figure 6-8 The BankBalance application Java Programming, Seventh Edition 20 Validating Data Ensuring data falls within a specific range Priming read Input retrieved before the loop is entered Within a loop, the last statement retrieves the next input value and checks the value before the next entrance of the loop

Java Programming, Seventh Edition 21 Validating Data (contd.) Figure 6-10 The EnterSmallValue application Java Programming, Seventh Edition 22 Using Shortcut Arithmetic

Operators Accumulating Repeatedly increasing a value by some amount Java provides shortcuts for incrementing and accumulating += -= *= /= %= add and assign operator

subtract and assign operator multiply and assign operator divide and assign operator remainder and assign operator Java Programming, Seventh Edition 23 Using Shortcut Arithmetic Operators (contd.) Prefix increment operator and postfix increment operator

++someValue, someValue++ Use only with variables Unary operators Use with one value Increase a variables value by 1 No difference between operators (unless other operations are in the same expression) Java Programming, Seventh Edition 24

Using Shortcut Arithmetic Operators (contd.) Figure 6-13 Four ways to add 1 to a value Java Programming, Seventh Edition 25 Using Shortcut Arithmetic Operators (contd.) Prefix increment operator and postfix increment operator (contd.)

Prefix ++ The result is calculated and stored Then the variable is used Postfix ++ The variable is used Then the result is calculated and stored Prefix and postfix decrement operators --someValue someValue- Similar logic to increment operators Java Programming, Seventh Edition

26 Using Shortcut Arithmetic Operators (contd.) Figure 6-14 The IncrementDemo application Java Programming, Seventh Edition 27 Creating a for Loop for loop Used when a definite number of loop iterations is required

One convenient statement indicates: The starting value for the loop control variable The test condition that controls loop entry The expression that alters the loop control variable Java Programming, Seventh Edition 28 Creating a for Loop (contd.) Figure 6-18 A for loop and a while loop that display the integers 1 through 10

Java Programming, Seventh Edition 29 Creating a for Loop (contd.) Other uses for the three sections of a for loop Initialization of more than one variable Place commas between separate statements Performance of more than one test using AND or OR operators Decrementation or performance of some other task Altering more than one value

You can leave one or more portions of a for loop empty Two semicolons are still required as placeholders Java Programming, Seventh Edition 30 Creating a for Loop (contd.) Use the same loop control variable in all three parts of a for statement To pause a program: Use the for loop that contains no body

for(x = 0; x < 100000; ++x); Or use the built-in sleep() method Java Programming, Seventh Edition 31 Learning How and When to Use a dowhile Loop dowhile loop A posttest loop Checks the value of the loop control variable

At the bottom of the loop After one repetition has occurred Performs a task at least one time You are never required to use this type of loop Use curly braces to block the statement Even with a single statement Java Programming, Seventh Edition 32 Learning How and When to Use

a dowhile Loop (contd.) Figure 6-20 General structure of a dowhile loop Java Programming, Seventh Edition 33 Learning How and When to Use a dowhile Loop (contd.) Figure 6-21 A dowhile loop for the BankBalance2 application Java Programming, Seventh Edition

34 Learning About Nested Loops Inner loop and outer loop An inner loop must be entirely contained in an outer loop Loops can never overlap To print three mailing labels for each of 20 customers: for(customer = 1; customer <= 20; ++customer) for(color = 1; color <= 3; ++color) outputLabel ();

Java Programming, Seventh Edition 35 Learning About Nested Loops (contd.) Figure 6-23 Nested loops Java Programming, Seventh Edition 36

Improving Loop Performance Make sure a loop does not include unnecessary operations or statements Consider the order of evaluation for short-circuit operators Make comparisons to 0 Employ loop fusion Java Programming, Seventh Edition 37

Avoiding Unnecessary Operations Do not use unnecessary operations or statements: Within a loops tested expression Within the loop body Avoid: while (x < a + b) // loop body Instead use: int sum = a + b; while(x < sum) // loop body

Java Programming, Seventh Edition 38 Considering the Order of Evaluation of Short-Circuit Operators Short-circuit evaluation Each part of an AND or an OR expression is evaluated only as much as necessary to determine the value of the expression Its important to consider the number of evaluations that take place

When a loop might execute many times Java Programming, Seventh Edition 39 Comparing to Zero Making a comparison to 0 is faster than making a comparison to any other value To improve loop performance, compare the loop control variable to 0 Do-nothing loop Performs no actions other than looping

Java Programming, Seventh Edition 40 Comparing to Zero (contd.) Figure 6-27 The CompareLoops application Java Programming, Seventh Edition 41 Employing Loop Fusion

Loop fusion A technique of combining two loops into one Will not work in every situation Java Programming, Seventh Edition 42 Using Prefix Incrementing Rather than Postfix Incrementing Prefix incrementing method ++x When the method receives a reference to x, the value is increased and

the increased value is returned Postfix incrementing method x++ When the method receives a reference to x, a copy of the value is made and stored The value is incremented as indicated by the reference The copy is returned The extra time spent copying causes postfix incrementing to take longer Java Programming, Seventh Edition 43

Using Prefix Incrementing Rather than Postfix Incrementing (contd.) Figure 6-29 The CompareLoops2 program Java Programming, Seventh Edition 44 You Do It

Writing a Loop to Validate Data Entries Working with Prefix and Postfix Increment Operators Working with Definite Loops Working with Nested Loops Comparing Execution Times for Separate and Fused Loops Java Programming, Seventh Edition 45

Dont Do It Dont insert a semicolon at the end of a while clause Dont forget to block multiple statements that should execute in a loop Dont make the mistake of checking for invalid data using a decision instead of a loop Dont ignore subtleties in the boundaries used to stop loop performance Dont repeat steps within a loop that could just as well be placed outside the loop Java Programming, Seventh Edition

46 Summary The loop structure allows repeated execution of a block of statements Infinite loop Definite loop Nest loop You must change the loop control variable within the looping structure Use the while loop to execute statements while some condition is true

Java Programming, Seventh Edition 47 Summary (contd.) Execute the while loop Initialize the loop control variable, test in the while statement, and alter the loop control variable Prefix ++ and postfix ++ Increase a variables value by 1 The variable is used The result is calculated and stored

Unary operators Use with one value Java Programming, Seventh Edition 48 Summary (contd.) Binary operators Operate on two values Shortcut operators +=, -=, *=, and /=

Perform operations and assign the result in one step for loop Initializes, tests, and increments in one statement dowhile loop Tests a Boolean expression after one repetition Improve loop performance Do not include unnecessary operations or statements Java Programming, Seventh Edition 49

Recently Viewed Presentations

  • ICALEPCS 2003 Session on Middleware

    ICALEPCS 2003 Session on Middleware

    Title: ICALEPCS 2003 Session on Middleware Author: Matthias Clausen Last modified by: DESYUser Created Date: 1/21/2003 8:11:47 PM Document presentation format
  • Le Pere Lachaise _ 2

    Le Pere Lachaise _ 2

    Corot a bâti une œuvre assez riche et variée pour avoir touché à tous les courants de l'époque. **** Corot Gilbert Bécaud ( 1927-2001 ) Il fut chanteur compositeur, pianiste et acteur. Sa célèbre cravate à pois qui était son...
  • RELA-OL - Humble Independent School District

    RELA-OL - Humble Independent School District

    REMIND. This used to be Remind 101, now it is just Remind. 1 way communication- I can text you, but you can't text back! (I will not make contact after the hours of 6pm or on weekends)
  • Photosynthesis - 2.files.edl.io

    Photosynthesis - 2.files.edl.io

    Outline Protist Biology Protist Evolution Protist Diversity Green Algae Red Algae Brown Algae Diatoms Dinoflagellates Protist Diversity, cont. Euglenoids Zooflagellates Pseudopods Ciliates Sporozoans Slime Molds Water Molds General Biology of the Protists Classified into the Domain Eukarya & the Kingdom...
  • Jeopardy - readington.k12.nj.us

    Jeopardy - readington.k12.nj.us

    Created by Jerry Myers is 1998 for a class. 100 100 200 200 400 400 300 400 vocabulary War important material the new colonies 300 300 300 200 400 200 100 500 500 500 500 100 Row 1, Col 1...
  • EASTER - IISS Rinaldo d&#x27;Aquino

    EASTER - IISS Rinaldo d'Aquino

    EASTER FOR THE english. The hunt for Easter eggs is a very fun tradition that comes from Northern Europe (English-speaking countries and German language and culture in the first place) that still did not take much foot in Italy (maybe...
  • The Liturgy of the Hours - De La Salle High School

    The Liturgy of the Hours - De La Salle High School

    The Liturgy of the Hours. The Sacraments. Document #: TX002086. Notes: Ask two students to participate as prayer leader and reader. Divide the class into two groups, side 1 and side 2, for the recitation of Psalm 91.
  • Bending the Tools Exceeding Expectations of Lifelong Learners

    Bending the Tools Exceeding Expectations of Lifelong Learners

    Bending the Tools Exceeding Expectations of Lifelong Learners through Flexible Learning Peter Le Cornu Program Director, Communication and Leadership