Chapter 6A While Loops Asserting Java © Rick Mercer.

Slides:



Advertisements
Similar presentations
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Advertisements

Repetition control structures
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 6 Repetition Asserting Java © Rick Mercer.
Chapter 5: Loops and Files.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
09 Non-deterministic iteration1June Non-deterministic iteration CE : Fundamental Programming Techniques.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 6 Repetition Asserting Java © Rick Mercer.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Chapter 5 Loops.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright © Curt Hill Loop Types and Construction Logical types and construction hints.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 6 Repetition Asserting Java © Rick Mercer.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II
Chapter 6, Part 1 While Loops Asserting Java © Rick Mercer 1.
Determinate Loop Pattern, Java's for Statement, and Scanner objects
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Java's for Statement.
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
TK1114 Computer Programming
Determinate Loop Pattern, Java's for Statement, and Scanner objects
Determinate Loops with the
Chapter 8 Repetition Computing Fundamentals with C++ 3rd Edition
Control Statements Loops.
Chapter 6 Repetition Asserting Java © Rick Mercer 1.
More Loops Topics Counter-Controlled (Definite) Repetition
Control Statements Loops.
Repetition Statements
Building Java Programs
Building Java Programs
More Loops Topics Counter-Controlled (Definite) Repetition
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Building Java Programs
Chapter 6, Part 1 While Loops Asserting Java © Rick Mercer 1.
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

Chapter 6A While Loops Asserting Java © Rick Mercer

Algorithmic Pattern: The Determinate loop  We often need to perform some action a specific number of times: — Produce 89 paychecks. — Count down to 0 (take 1 second of the clock). — Compute grades for 81 students  The determinate loop pattern repeats some action a specific number of times.

Determinate Loops Determinate Loops  The determinate loop pattern can be implemented with the Java while loop  This template executes some statements n times: — determinate loops must know the number of repetitions before they begin: know exactly how many employees, or students, or whatever that must be processed, for example int n = 0; /* how often we must repeat */ int counter = 1; while (counter <= n) { // TODO: Add the steps to be repeated counter = counter + 1; }

While loop output  What is the output? int j = 1; int n = 5; while (j <= n) { System.out.print(j + " "); j = j + 1; } j = 2 * n; while (j >= 0) { System.out.print(j + " "); j = j - 2; }

Problem Solving The Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum of the two preceding elements. Write int fib(int n) to return the n th Fibonacci public void testFib() { LoopFun loops = new LoopFun(); assertEquals(1, loops.fib(1)); assertEquals(1, loops.fib(2)); assertEquals(2, loops.fib(3)); assertEquals(3, loops.fib(4)); assertEquals(5, loops.fib(5)); assertEquals(8, loops.fib(6)); assertEquals(13, loops.fib(7)); assertEquals(21, loops.fib(8)); }

Indeterminate Loops  Determinate loops have a limitation — We must know n (the number of repetitions) in advance  Many situations need us to repeat a set of statements an unspecified number of times: — Processing report cards for every student in a school (or paychecks for all employees, or...) — Allowing 1 to many ATM transactions — Asking the user for specific input and allowing re-entry of input after invalid inputs

Change DeterminateLoop.java to an indeterminate loop:  Sometimes a stream of input from the keyboard or a file needs to be read until there is no more data in the input stream  Consider using a special value of the same type that is not meant to be processed — Perhaps a negative integer for tests that range from 0 through 100 only — Code Demo: Change DeterminateLoop to read until there is a sentinel (like things we will do in lab)

Some things that terminate indeterminate loops  An indeterminate loop repeats a process until some stopping event terminates the repetition  There are many such events, but we'll focus on these: — User enters a special value indicating end of data — A logical expression becomes false — The Grid's mover hits the wall or an edge — The end of a file is encountered  Indeterminate loops do not need to know n in advance  Indeterminate loops can actually determine n

Pattern Indeterminate loop Problem Some process must repeat an unknown number of times so some event is needed to terminate the loop. Algorithm while( the termination event has not occurred ) { Execute these actions bring the loop closer to termination } Code while(myGrid.frontIsClear()) { Example myGrid.move( ); }

// Using random robot placement, instruct the // robot to get to the wall in front. // // This program needs Grid.java in the same project // public class MoveAroundTheGrid { public static void main(String[] args) { // When using this 2 argument constructor, the // grid is surrounded by blocks with one "exit" // and the mover is facing a random direction // after being placed in a random location. Grid g = new Grid(10, 15); // Always get to a wall or the lone exit if lucky while (g.frontIsClear()) { g.move(); } }

While loop with a Scanner While loop with a Scanner  Sometimes a stream of input from the keyboard or a file needs to be read until there is no more data in the input stream  Consider a Scanner object constructed with a String argument — The string represents an input stream  You will need Scanner in project

These assertions public void showScanner() { Scanner scannerWithInts = new Scanner("1 2 3"); assertEquals(1, scannerWithInts.nextInt()); assertEquals(2, scannerWithInts.nextInt()); assertEquals(3, scannerWithInts.nextInt()); Scanner scanner = new Scanner("There are five words here."); assertEquals("There", scanner.next()); assertEquals("are", scanner.next()); assertEquals("five", scanner.next()); assertEquals("words", scanner.next()); assertEquals("here.", scanner.next()); }

A test method to test public void testNum100s() { LoopFun lf = new LoopFun(); Scanner scanner0 = new Scanner("1 2 3"); Scanner scanner1 = new Scanner(" "); Scanner scanner3 = new Scanner(" "); assertEquals(0, lf.num100s(scanner0)); assertEquals(1, lf.num100s(scanner1)); assertEquals(3, lf.num100s(scanner3)); }

Answer Answer public int num100s (Scanner scanner) { int result = 0; while (scanner.hasNextInt()) { int next = scanner.nextInt(); if (next == 100) result++; } return result; }

Careful using next too often!  These assertions should pass with the code that follows on the next public void testSumOfNegs() { ControlFun lf = new ControlFun(); Scanner scanner0 = new Scanner("1 2 3"); Scanner scannerA = new Scanner("1 -2 3"); Scanner scannerB = new Scanner(" "); assertEquals(0, lf.sumOfNegatives(scanner0)); assertEquals(-2, lf.sumOfNegatives(scannerA)); assertEquals(-6, lf.sumOfNegatives(scannerB)); }

What's wrong with this method? What's wrong with this method? public int sumOfNegatives(Scanner scanner) { int result = 0; while (scanner.hasNextInt()) { if (scanner.nextInt() < 0) { result += scanner.nextInt(); } return result; }