Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC

Slides:



Advertisements
Similar presentations
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 4: Control Structures II
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Java Programming: From the Ground Up
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Java Fundamentals 4.
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II
Loops.
Lecture 7: Repeating a Known Number of Times
Chapter 5: Control Structures II
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
Loop Structures.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
Control Structures - Repetition
Chapter 4 Control structures and Loops
MSIS 655 Advanced Business Applications Programming
Control Statements Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Computing Fundamentals
Objectives You should be able to describe: The while Statement
Suggested self-checks:
Control Statements Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Loops and Iteration CS 21a: Introduction to Computing I
Chapter 3 Flow of Control Loops in Java.
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC Most of the material in this file is derived from Introduction to Java Programming, 8th Edition by Daniel Liang

§4.1 Introduction So far, all of our code has been sequential The program starts at the top, and proceeds towards the bottom if and switch statements may allow us to skip over some lines of code, but we're still constantly moving down towards the bottom of the program Loops allow us to repeat one or more lines of code as many times as we want

§4.1 Introduction Suppose we want to print a table of the square roots of the integers from 1 to 100: System.out.println(1 + ":square root = " + Math.sqrt(1)); System.out.println(2 + ":square root = " + Math.sqrt(2)); System.out.println(3 + ":square root = " + Math.sqrt(3)); System.out.println(4 + ":square root = " + Math.sqrt(4)); System.out.println(5 + ":square root = " + Math.sqrt(5)); … There must be a better way! There is – use a loop

§4.1 Introduction Java has three types of loop that we can use to execute code over and over: while do…while for

Section 4.2 The while Loop

§4.2 The while Loop The syntax of the while loop: while (condition) { statement(s); } As with the if-then and if-then-else statements, if statement(s) consists of a single statement, then the braces are optional. The statement(s) will continue to be executed as long as condition remains true

§4.2 The while Loop while (condition) { statement(s); } Think of the while loop as running until (!condition)

Loop continuation condition §4.2 The wihle Loop The square root problem: int count = 1; while (count <= 100) { System.out.println( count + ":square root = " + Math.sqrt(count)); count++; } One pass through the body of the loop is called an iteration Loop continuation condition Loop Body

§4.2 The while Loop In the square root problem, we knew how many times we wanted the loop to execute, so we counted each iteration This is an example of a counter-controlled loop In the case of a counter-controlled loop, we must increment the counter in each iteration, and our loop-continuation-condition must check the counter every iteration Note: some loops will count from a higher starting value down towards 1 (or zero), and we decrement the counter in each iteration

§4.2 The wihle Loop Section 4.2.1 implements a hi-low number guessing game The program picks a random number between 0 and 100 (inclusive) The user guesses numbers until they guess the number For each user guess, the program tells the user if they are too high or too low

§4.2 The while Loop The book reminds us about good programming practice – don't start by writing code! Start by examining the problem, and determining how we can go about solving it We should program incrementally – when we do start writing code, we don't necessarily have to start at the top and write everything all at once, top-to-bottom, in one pass We can write it in pieces, and then assemble the pieces

§4.2 The while Loop Loop design strategies: Identify the statements that need to be repeated (i.e., the body of the loop Wrap the statements in the condition / braces syntax Code the loop-continuation-condition and add the appropriate statements for controlling the loop

§4.2 The Hi-Lo Guessing Game (1) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); }

§4.2 The Hi-Lo Guessing Game (2) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); }

§4.2 The while Loop Rather than counting iterations through the loop, sometimes we want the body of the loop to run some unknown number of times, until something happens We may determine when to exit the loop based on some special value whose only significance is to end the program Such a value is called a sentinel value, and such a loop is called a sentinel-controlled loop

§4.2 The wihle Loop Be careful using float or double values as loop control variables Recall that floating point math is not exact!! If your loop is looking for a particular value to determine when to stop, it may never see it, because it's off a little in the 15th decimal place! Rather than using ==, use <= or >=

§4.3 The do-while Loop The do-while loop is a subtle variation on the while loop do { Statement(s); // Loop body; } while (loop-continuation-condition);

§4.3 The do-while Loop The biggest difference between the while and do-while loops is that checking the condition in a do-while loop follows the loop body; in a while loop, checking the condition precedes the loop body This means that the body of a while loop will execute zero or more times; the body of a do-while loop will execute one or more times In other words, the body of… …a do-while loop is guaranteed to run at least once …a while loop is not guaranteed to run at all!

§4.2 The Hi-Lo Guessing Game (2) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } This is a repeat of the slide we saw earlier

§4.2 The Hi-Lo Guessing Game (3) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); do // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } while (guess != number); }

Section 4.4 The for Loop

§4.4 The for Loop A counter-controlled loop is usually written in an alternate form – a for loop – rather than as a while loop Functionally, they're the same, but for some operations, the for loop is much clearer to read A counter-based while loop: Initializes the counter, Has a condition it tests before each iteration, and Modifies the counter each iteration So does a for loop!

§4.4 The for Loop Let's revisit our square roots of 1-100 program: int count = 1; while (count <= 100) { //compute & output sqrt count++; } We can do the same thing with a for loop: for (int count = 1; count <= 100; count++) // compute & output sqrt

§4.4 The for Loop The syntax of the for loop is: for (initialize step(s); loop-continuation-condition; update step(s)) { statement(s); } The initialize, condition, and update parts of the for loop are separated by semicolons, and the whole thing must be enclosed in parentheses Typically, they're all coded on the same line

§4.4 The for Loop for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } As with the while loop, it's possible that the body of a for loop is never executed

§4.4 The for Loop Because the for loop is almost always used to implement a counter-controlled loop: The initial-action will be to assign the starting value to the loop control variable (i.e., the counter) The loop-continuation-condition will be that the loop counter is less than its final value The action-after-each-iteration will be to increment the loop counter for (i = 1; i <= 100; i++) As we have seen before, if the body of the loop is a single statement, the braces are optional

§4.4 The for Loop If the loop counter is only needed within the loop (i.e., it's not some variable that the program needs outside the loop), it's good programming practice to declare the loop counter in the for statement: for (int i = 0; i<100; i++)… Declaring the loop counter in the for statement means that after the loop, the loop variable no longer exists Restricting the visibility of the loop variable, such that it only exists where it is needed, is good practice This is known as the scope of a variable (Chapter 5)

§4.4 The for Loop Sometimes, we'll want to do more than one thing to set up the loop. Perhaps we have one counter (i) that needs to count up from 0, and another counter (j) that needs to count down from 100 at the same time We can separate multiple initialization and/or update steps with commas: for (i=1, j=100; i<=100; i++, j--)

§4.4 The for Loop These two are equivalent: for (i=1, j=100; i<=100; i++, j--) { // body statement(s); } i = 1; j = 100; while (i <= 100) i++; j--;

§4.4 The for Loop Finally, the three parts of the for statement are all optional, but they're rarely omitted If the initialization or update is omitted, then no initialization or update is performed If the loop-continuation-condition is omitted, it is assume to be true All of the following set up infinite loops: for (;;) { } for (;true;) { } while (true) { }

Which Kind of Loop to Use? Section 4.5 Which Kind of Loop to Use?

§4.5 Which Loop to Use? The while and for loops are known as pre-test loops – they test the condition before each iteration of the loop This means the body of these loops will execute zero or more times The do…while loop is a post-test loop – it tests the condition after each iteration of the loop This means the body of a do…while loop will execute one or more times

§4.5 Which Loop to Use? Recommendations: If you need to make sure the body of your loop runs at least once, use do…while If you know ahead of time how many times the body of the loop needs to run – i.e., a count-controlled loop, use for If you need to have the loop run until some event occurs (but there's no way of telling how many times the loop might need to run to get that even to occur), use while or do…while When there's no compelling reason to use a particular kind, use whatever is most intuitive and comfortable

§4.5 Common Loop Errors (1) Don't put a semicolon after the parenthesis: for (i = 1; i <= 100; i++); { // loop body } This will execute what we labeled as being the loop body (i.e., what's between the braces) once The loop's REAL body is the null statement created by the semicolon This loop, as written, will do nothing, 100 times

§4.5 Common Errors (2) A do…while loop DOES have to have a semicolon after the condition: for (init;cond;update) stmt; for (init;cond;update) { } while(condition) stmt; while(condition) { } do stmt while (cond); do { } while (cond);

§4.5 Common Errors (3) Watch the boundary conditions: for (i = 1; i <= 100; i++) This will execute the body for i = 1 through 100 for (i = 1; i < 100; i++) This will execute the body for i = 1 through 99 for (i = 1; i < 100; i+=2) This will execute the body for i = 1, 3, 5, …, 99

Section 4.6 Nested Loops

§4.6 Nested Loops When we looked at if-then-else statements in Chapter 3, we said that the statement(s) in the then and else clauses could be any legal Java statement, including another if statement We called this a nested if statement When it comes to loops, the same thing applies; the body of a loop can contain another loop We call this a nested loop When loops are nested, the inner loop runs for each iteration of the outer loop

§4.6 Nested Loops for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) System.out.println("hello"); } How many times will this print "hello"?

§4.6 Nested Loops for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) System.out.println(i + "," + j); } What will this print?

§4.6 Nested Loops Nested loops are often used for tables The outer loop iterates through the rows The inner loop iterates through the columns of the current row

§4.6 Nested Loops – Example (p.129) System.out.print(" | "); for (int i = 1; i <= 9; i++) System.out.print(" " + i); System.out.println("\n---+-----------------"); for (int row = 1; row <= 9; row++) { System.out.printf("%3d|", row); for (int col = 1; col <= 9; col++) System.out.printf("%4d", row*col); System.out.println(); } | 1 2 3 4 5 6 7 8 9 ---+--------------------------- 1| 1 2 3 4 5 6 7 8 9 2| 2 4 6 8 10 12 14 16 18 3| 3 6 9 12 15 18 21 24 27 4| 4 8 12 16 20 24 28 32 36

Keywords break & continue Section 4.9 Keywords break & continue

§4.9 The Keywords break & continue Normally, you should let the loop control variable handle controlling the execution of a loop There are special occasions during which it makes sense to override the standard loop execution break and continue can be used to alter the flow of code through a loop Using them indiscriminately or improperly can make your code harder to read and debug

§4.9 The Keywords break & continue break aborts execution of a loop The break statement passes control to the first statement after the end of the loop In the case of nested loops, break terminates only the loop in which it appears (unless you use a labeled block) continue can be used to terminate the current loop iteration – control goes to the end of the loop body (directly to checking the loop control condition) continue aborts the current iteration; break aborts the entire loop

§4.9 The Keywords break & continue while loop do…while loop for loop break aborts the whole loop the first statement after the loop is executed next continue aborts (skips the remaining statements in) the current iteration For do…while and while loops, the condition is evaluated; For for loops, the update action is performed and then the condition is checked

§4.2 The Hi-Lo Guessing Game (2) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } This is a repeat of the slide we saw earlier

§4.2 The Hi-Lo Guessing Game (4) import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); while (true) // we'll exit when the user guesses correctly // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); break; } else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low");

End of Chapter 4 Any Questions?