CS112 Lecture: Repetition Statements

Similar documents
CS112 Lecture: Loops

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition, Looping CS101

C++ Programming: From Problem Analysis to Program Design, Third Edition

CS110D: PROGRAMMING LANGUAGE I

Lecture Transcript While and Do While Statements in C++

Introduction. C provides two styles of flow control:

3 The L oop Control Structure

CS112 Lecture: Making Choices

Repetition Structures

(Refer Slide Time: 00:26)

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

REPETITION CONTROL STRUCTURE LOGO

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

STUDENT LESSON A12 Iterations

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

LESSON 3 CONTROL STRUCTURES

Computer Programming I - Unit 5 Lecture page 1 of 14

CIS 3260 Intro to Programming in C#

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

LOOPS. Repetition using the while statement

Unit 1 Lesson 4. Introduction to Control Statements

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Flow of Control: Loops

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Repetition, Looping. While Loop

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

LECTURE 5 Control Structures Part 2

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Programming Lecture 4

Introduction to the Java Basics: Control Flow Statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

CS112 Lecture: Defining Instantiable Classes

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Programming Lecture 4

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

In this chapter you will learn:

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Repetition and Loop Statements Chapter 5

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Text Input and Conditionals

Chapter 3. Iteration

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Information Science 1

CS 106 Introduction to Computer Science I

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter Two: Program Design Process and Logic

Quiz Determine the output of the following program:

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

More about Loops and Decisions

Unit 3 Decision making, Looping and Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Control Structures II. Repetition (Loops)

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Chapter 4 Introduction to Control Statements

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

More on control structures

Example: Monte Carlo Simulation 1

Chapter 5: Control Structures II (Repetition)

CS 106 Introduction to Computer Science I

Loops / Repetition Statements

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Problem Solving With Loops

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Introduction to Computer Programming

Programming for Electrical and Computer Engineers. Loops

V3 1/3/2015. Programming in C. Example 1. Example Ch 05 A 1. What if we want to process three different pairs of integers?

Transcription:

CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general form of the java for loop. 4. To discuss pitfalls in writing loops 5. To introduce the use of continue and break in loop bodies Materials: 1. Transparencies from Wu of flowcharts for while, do.. while, and for loops (figures 6.2, 6.4, 6.8) and corresponding code 2. Transparencies of priming the pump and input validation pattern examples. 3. Original relay race project code; option 2, FailedRelayRace.java,.class; RelayRace.world; SuccessfulRelayRace.java,.class 4. Transparency of Wu table 7.1 (2nd ed) 5. Executable of Dr. Java I. Introduction A. In our discussion of Karel the Robot, we were introduced to the Java repetition statements while ( <condition> ) <statement> AND for (int <var> = <initial>; <var> < <final>; <var> ++) <statement> As we noted at that time, these are general Java statements, and are useful for a variety of purposes beyond moving robots around in their world. In the case of the for statement, the Java statement is actually much more general than the form we learned about. In addition, there is another Java repetition statement we didn t even discuss. B. Recall that we saw with Karel that the <statement> comprising the body of a loop may either be: 1

1. A single statement 2. A compound statement enclosed in braces. This is true in general in Java, not just with Karel II. The while Statement A. The while statement in Java is the simplest of the three looping statements we will learn about. B. The <condition> that is specified can be any boolean expression - so everything we said about boolean expressions in connection with if statements also applies to while statements. C. It is important to bear in mind exactly when the condition is tested: 1. It is tested initially, before the first entry into the body of the loop. Thus, it is possible for a while loop body to be done zero times. 2. It is tested after each completion of the loop body, in order to decide whether to do the body again. 3. A consequence of the above two facts is that the condition is always tested one more time than the number of times through the body of the loop. Each time it tests true, the body of the loop is executed; the one time it tests false, the loop terminates. 4. The condition is not tested in the middle of the loop body - so it can become momentarily false without necessarily leading to loop termination. 5. Summary: Wu gives a flow chart that summarizes the flow of control in a while loop, for the following problem: Calculate the sum of the integers from 1 to 100. (By actually adding them - you may know a mathematical shortcut to arrive at the answer more simply) CODE: 2

int sum = 0, number = 1; while (number <= 100) sum = sum + number; number = number + 1; TRANSPARENCY - Above code, Wu figure 6.2 D. There are some important and useful patterns that arise in conjunction with while loops. 1. One such pattern is the priming the pump pattern that frequently arises in conjunction with sentinel values. Example: Suppose we wanted to write a program to calculate the average grade on the exam. Rather than asking the user to count the number of grades ahead of time, we will allow the user to just enter the scores, entering a value of -1 when finished. We ll assume we have a dialog called inputbox with a method called getfloat() that gets a float value TRANSPARENCY float sum = 0; float count = 0; float grade = inputbox.getfloat("enter first grade:"); while (grade >= 0) sum = sum + grade; count ++; grade = inputbox.getfloat( "Enter next grade or - 1 if done:"); float average = sum / count; a) The value -1 that the user enters to terminate the loop is called the sentinel value. (1) The sentinel value must be chosen to be one that cannot possibly be a legitimate value for the program to process. Here, we assume that a negative grade on an exam is impossible. 3

(2) The sentinel value can either be couched as a single value, or as a set of values that meet some criterion. (E.g. as the example program is written, any negative value the user enters would suffice. This is good defensive programming.) (3) Care must be used in choosing the sentinel value - lest surprising things happen. Example: One time a company s payroll system stopped paying employees with names beginning with DR and up. Upon examination, it was found that the company had recently hired a person whose name was DONE. Unfortunately, the authors of the payroll program had used an employee name of DONE as the sentinel for indicating the end of the list of employees! (4) In some cases, if all possible values of input could be legitimate, a sentinel-controlled loop cannot be used. b) A characteristic of the sentinel-controlled loop - called the priming the pump pattern is that the step that ultimately produces the sentinel value (here the call to inputbox.getfloat) occurs twice: (1) Once before the initial entry to the loop (to prime the pump) (2) Once at the very end of the loop body (to get the value that decides whether or not we go around again.) (3) This is a consequence of the fact that the statement that produces the sentinel is done one more time than the rest of the statements in the loop body - because the last time it is done, it produces the sentinel value and the loop body is not done. 2. Another pattern could be called the input validation pattern. Suppose we wanted to ensure that the grade entered was never greater than 100. 4

float sum = 0; float count = 0; float grade = inputbox.getfloat("enter first grade:"); while (grade >= 0) while (grade > 100) grade = inputbox.getfloat( "Please enter a value not greater than 100:"); sum = sum + grade; count ++; grade = inputbox.getfloat( "Enter next grade or - 1 if done:"); float average = sum / count; TRANSPARENCY a) This code actually has a problem. What is it? If the user enters a grade greater than 100, and then, upon re-entry, enters a negative grade, the value is processed as if it were a valid grade. b) To fix, we would need to validate each time input is requested 5

III. The do... while loop float sum = 0; float count = 0; float grade = inputbox.getfloat("enter first grade:"); while (grade > 100) grade = inputbox.getfloat( "Please enter a value not greater than 100:"); while (grade >= 0) sum = sum + grade; count ++; grade = inputbox.getfloat( "Enter next grade or - 1 if done:"); while (grade > 100) grade = inputbox.getfloat( "Please enter a value not greater than 100:"); float average = sum / count; Note: the input validation pattern is distinct from the priming the pump pattern - e.g. we might use it without the priming the pump pattern if we did not need the former. A. One important characteristic of the while loop is that its body can be done zero or more times. Related to that is the necessity of ensuring that the variables involved in the condition being tested have appropriate initial value set before encountering the loop (e.g. priming the pump). B. There are some situations in which the logic of what is being done mandates that the loop body be done at least once. Often, the first time through the loop is special in some way in these cases. 1. Example: Consider the Karel the Robot steeple chase project. As you recall, option two involved turning this into a relay race, using two robots. It turns out that this change could be made by creating two classes of robots, one of which extends the other and overrides one method. Show code for runrace() method of SteepleChaseRobot and RelaySteepleChaseRobot. Note that the only difference is that the former runs until it is next to a beeper, and the latter until it is next to a robot. All other methods are inherited 6

2. Now consider a further modification to use three robots. The first runs to the second, the second to the third, and the third to the finish. It would appear at first that we can do this by the same approach, using two classes, with two instances of the relay class and one of the finisher class. Show code for main method of incorrect version DEMO - run slowly near handoff to second relay robot 3. Why did this code exhibit the problem? ASK The program crashes because the second robot (doofus) stops where he starts, dropping the beeper torch there, and leading the third robot to try to pick up a beeper torch that has not yet been delivered, leading to an error shutoff. Recall that the runrace() loop for the relay robot looks like this: while (! nexttoarobot()) advanceoneblock(); Now consider what happens to the doofus. We want him to run until he is next to zelda. However, when he starts out, he is still next to the anthony (who has just handed off the beeper torch.) Since the nexttoarobot test succeeds if a robot is next to any other robot, the while loop terminates immediately, leading to the error condition. C. Situations like this can be handled by using a different sort of loop - the do.. while loop: do <statement> while <condition> 1. In this form of loop, the rules for <statement> and <condition> are the same as for the ordinary while loop a) The statement can either be a single statement or a compound statement (enclosed in braces). b) The condition can be any boolean expression. Note that, as in the ordinary while loop, the condition being true causes us to continue executing the loop. 7

2. In this form of loop, the first iteration is special, and is always done. The loop condition is not tested until after the first iteration completes. Wu gives a flow chart that summarizes the flow of control in a do.. while loop, for the following problem: Calculate the sum of the integers 1, 2, 3,... until the sum becomes greater than 100,000. CODE: int sum = 0, number = 1; do sum += number; number ++; while (sum <= 100000); TRANSPARENCY - CODE, then Wu figure 6.4 3. Our failed relay race could be handled successfully by changing the while loop in the runrace() method of the initial robots to a do..while SHOW CODE for runrace() method of GoodRelaySteeplechaseRobot in SuccessfulRelayRace.java DEMO 4. Note that each type of loop (while and do.. while) has its appropriate uses, and some thought should be given as to which type of loop is most appropriate in any given case. EXAMPLE: Show code for runrace() method of SteepleChaseRobot. It still uses a while loop, not a do.. while. Why? ASK Because we do want to allow for the possibility of this loop being done zero times, if the robot starts out on the square containing the beeper that marks the end of the race (as in one of the test worlds for this project). Note that if a while loop is used here, a special case if statement (as some students used in a previous year) is not needed. 8

5. For the grade averaging example we did earlier, could we change the while loop to a do.. while? Should we have? ASK a) A do.. while is appropriate in this case, because we cannot compute a meaningful average if there are no grades. (We would get a divide by zero error when we divide by count). b) Note that changing to a do.. while does not eliminate the need for the priming read in this case. We still have to read one more grade than we actually use. IV. The Java for Loop A. The final kind of loop we need to consider is the for loop. It has the general form: for ( < initialization > ; < test > ; < increment > ) < statement > where 1. Initialization is zero or more initializations of variables (separated by commas) to be done before the loop is entered the first time. a) It is possible to declare variables in the initialization - in which case the scope of the variable is limited to just the loop EXAMPLE: for (int i = 0; i < 10; i ++) System.out.println(i); // Declaration of i is no longer in effect here b) The initialization part of the loop can be empty, but the semicolon is still required. 2. Test is a condition to be tested before entering the loop each time (as in a while loop) 9

3. Increment is zero or more assignments of variables (separated by commas) to be done after each time through the loop body. a) Frequently, the increment part makes use of the Java increment (++), decrement (--), and/or shorthand assignment operators TRANSPARENCY - Wu table 7.1 b) The increment part of the loop can be empty, but the semicolon is still required. 4. As with other kinds of loop, statement can either be a single statement or a compound statement enclosed in braces. 5. Wu gives a flow chart that summarizes the flow of control in a for loop, for the following problem: Add up the first 100 integers (the hard way!) CODE: int i, sum = 0; for (i = 1; i <= 100; i ++) sum += i; The following flowchart shows the relative sequence of the various operations TRANSPARENCY - Code, Wu figure 6.8 B. In fact, a for loop like the above is exactly equivalent to the following while loop: < initialization > while ( < test > ) < statement >; < increment >; 10

C. Most frequently, the for loop is used for counter-controlled loops, in which case 1. The initialization creates a counter variable and initializes it (most often to 0 or 1; sometimes to a maximum value if we want to count backwards) 2. The test checks to see if the counter variable has reached its limit yet. 3. The increment steps the counter to the next value 4. EXAMPLE: Print the square roots of numbers in the range of 1.0 up to (but not including) 2.0 in steps of 0.1 for (double x = 1.0; x < 2.0; x += 0.1) System.out.println("sqrt(" +x+ ") = "+Math.sqrt(x)); DEMO using Dr. Java 5. EXAMPLE: Calculate and print the powers of 2 up to 230 (the largest power of 2 representable as a Java int). (Note the use of two local variables declared in the initialization and modified by the increment) for (int i = 0, n = 1; i <= 30; i ++, n *= 2) System.out.println("2 to the power " +i+ "=" +n); DEMO using Dr. Java D. As a general rule of thumb, to which there are certainly exceptions, one should use the various types of loops as follows: 1. For indefinite iteration, where the loop body can be done zero or more times: use a while loop 2. For indefinite iteration, where the loop body must be done at least once: use a do... while loop 3. For definite iteration: use a for loop 11

V. Pitfalls in Writing Loops There are several pitfalls to watch out for when writing loops A. Infinite loops: Always be sure that you can convince yourself that the loop will eventually terminate - i.e. that the loop condition will eventually become false. B. Exact count with floats: beware of a loop body whose test is designed to terminate the loop on exact equality with some value, especially when the value is a float EXAMPLE: Demonstrate the following loop with Dr. Java: for (float f = 1.0f; f!= 2.0f; f += 0.1f) System.out.println(f); (Use Reset Interactions in Tools menu to stop) Would changing from float to double solve the problem? ASK DEMO To solve the problem, we must switch the end test from requiring exact equality to <= DEMO C. Off by one errors: a very common error with loops is to make a slight error that results in the loop body being executed one too many times EXAMPLE: // turnleft() three times for (int i = 0; i <= 3; i ++) turnleft(); What does this actually do? ASK Turns left four times. 12

VI. Using the continue and break Statements in Loops A. All three of the standard java loops incorporate a boolean expression that is tested once per iteration in order to decide whether to (re) enter the loop. B. Sometimes, a condition may arise in the middle of a loop that calls for an immediate exit from the loop. EXAMPLE: Suppose we were writing a loop that repeatedly reads and totals the cost of individual items purchased. Suppose further that we want to exit the loop immediately if the customer exceeds some predetermined spending limit. 1. Java allows a break statement (just like the one we saw in conjunction with switch) to occur inside the body of a loop. If it is executed, the loop containing it is terminated immediately. EXAMPLE: (Continuing the above - using pseudocode) total = 0; do // Note - loop terminates early if total would // exceed limit purchase = get next purchase amount from user; if (purchase + total > limit) tell user (s)he d go over the limit; break; total = total + purchase; ask if user wants to enter another item while (user wants to enter another) 2. In the case of nested loops, a break always exits the innermost loop containing it. It is also possible to attach a label to a loop and exit a loop other than the innermost one by specifying the label, but we won t go into this here. C. Java also has a similar statement called continue that can be used inside a loop to specify that we start a new iteration of the loop immediately, rather than terminating the loop. (The loop may still terminate if the condition for staying in it is false.) 13

D. The Wu text does not discuss either continue or the usage of break within a loop, for good reason. The misuse of these statements can easily lead to confusing code - especially continue. In general, anytime you contemplate using one of these, you should ask if it s really the clearest way to write the code. Some writers would argue that the continue statement is never the best way to write something and so should not be used at all. (It s a carryover from C). EXAMPLE: The above loop written without using break: total = 0; overlimit = false; do purchase = get next purchase amount from user; if (purchase + total > limit) tell user (s)he d go over the limit; overlimit = true; else total = total + purchase; ask if user wants to enter another item while (! overlimit and wants to enter another) Which solution is clearer and more readable? ASK Note use of comment to highlight possibility of mid-exit in first form 14