Flow of Control: Loops. Chapter 4

Similar documents
Flow of Control: Loops

Flow of Control: Loops

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

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

4. Flow of Control: Loops

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

Flow of Control. Chapter 3. Chapter 3 1

Repetition, Looping. While Loop

STUDENT LESSON A12 Iterations

Loops. CSE 114, Computer Science 1 Stony Brook University

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Repetition CSC 121 Fall 2014 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Repetition and Loop Statements Chapter 5

1 Short Answer (10 Points Each)

Controls Structure for Repetition

Problem Solving With Loops

Loops / Repetition Statements

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Example: Monte Carlo Simulation 1

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

Program Control Flow

Program Control Flow

Chapter Goals. Contents LOOPS

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

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

Top-Down Program Development

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

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

Repetition Structures

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

More on control structures

Lesson 7 Part 2 Flags

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

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

Java is an objet-oriented programming language providing features that support

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

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

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

CS1004: Intro to CS in Java, Spring 2005

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Last Class. While loops Infinite loops Loop counters Iterations

CS110D: PROGRAMMING LANGUAGE I

Darrell Bethea May 25, 2011

ECE 122. Engineering Problem Solving with Java

Chapter 17. Iteration The while Statement

Repetition, Looping CS101

Iteration statements - Loops

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Midterm Examination (MTA)

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

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Full file at

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Flow of Control. Chapter 3

Loops. Repeat after me

Conditional Execution

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Control Structures: if and while A C S L E C T U R E 4

St. Edmund Preparatory High School Brooklyn, NY

Loops (while and for)

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

COMP Introduction to Programming If-Else Statement, Switch Statement and Loops

COMP 110 Introduction to Programming. What did we discuss?

Oct Decision Structures cont d

Java Coding 3. Over & over again!

Introduction to Programming Using Java (98-388)

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

REPETITION CONTROL STRUCTURE LOGO

3chapter C ONTROL S TATEMENTS. Objectives

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

204111: Computer and Programming

CS1150 Principles of Computer Science Loops (Part II)

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CONDITIONAL EXECUTION: PART 2

Flow of Control. Chapter 3

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

CS112 Lecture: Repetition Statements

Chapter 3. More Flow of Control

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Programming with Java

CMPT 125: Lecture 4 Conditionals and Loops

MEDIA COMPUTATION DRJAVA. Lecture 11.3 November 7, 2008

CSIS 10A Assignment 4 SOLUTIONS

1 Short Answer (5 Points Each)

Transcription:

Flow of Control: Loops Chapter 4

Java Loop Statements: Outline The while statement The do-while statement The for Statement

Java Loop Statements A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is called the body of the loop. Example: A loop could be used to compute grades for each student in a class. There must be a means of exiting the loop.

The while Statement Also called a while loop A while statement repeats while a controlling boolean expression remains true The loop body typically contains an action that ultimately causes the controlling boolean expression to become false.

The while Statement Syntax while (Boolean_Expression) { First_Statement Second_Statement }

The while Statement Download, compile, and run WhileDemo.java Sample screen output

The do-while Statement Also called a do-while loop Similar to a while statement, except that the loop body is executed at least once Syntax do { Body_Statement } while (Boolean_Expression); Don t forget the semicolon!

The do-while Statement View DoWhileDemo.java Sample screen output

The do-while Statement First, the loop body is executed. Then the boolean expression is checked. As long as it is true, the loop is executed again. If it is false, the loop is exited. Equivalent while statement Statement(s)_S1 while (Boolean_Condition) { Statement(s)_S1 }

Using while to Read Input Download WhileWithScanner.java from the Examples link on the course webpage Compile and run a few times until you are comfortable with what the program does and how it does it.

Exercise Modify WhileWithScanner.java so that it reads one line of doubles, prints the intermediate results, and finally prints the sum for the entire line. Read a whole line from keyboard into a String Create a Scanner object on that String Proceed as before, but with the new Scanner

Infinite Loops A loop which repeats without ever ending is called an infinite loop. If the controlling boolean expression never becomes false, a while loop or a do-while loop will repeat without ending. Make sure a loop contains a statement which causes the boolean expression to become false eventually.

Nested Loops The body of a loop can contain any kind of statements, including another loop. View ExamAverager.java Sample screen output

Exercise Modify WhileWithScanner.java Add an outer loop that reads an entire line of input The inner loop calculates the sum for the current line of input

The for Statement A for statement executes the body of a loop a fixed number of times. Example for (count = 1; count < 3; count++) { } System.out.println(count);

The for Statement Syntax for (Initialization, Condition, Update) Body_Statement Body_Statement can be either a simple statement or a compound statement in {}. Corresponding while statement Initialization while (Condition) Body_Statement_Including_Update

The for Statement View ForDemo.java Sample screen output

The for Statement Possible to declare variables within a for statement int sum = 0; for (int n = 1 ; n <= 10 ; n++) { sum = sum + n * n; } Note that variable n is local to the loop

for Exercise Write a program called ReverseWords that reads lines of text from the keyboard and prints the line backwards Example: input: what's up? output:?pu s'tahw

for Exercise public class ReverseWords { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter text to be reversed: "); String line = keyboard.nextline(); for (int i = line.length()-1; i >= 0; i--) { System.out.print(line.charAt(i)); } System.out.println(""); } }

The for-each Statement Possible to step through values of an enumeration type Example enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES} for (Suit nextsuit : Suit.values()) { } System.out.print(nextSuit + " "); System.out.println();

Controlling Number of Loop Iterations If the number of iterations is known before the loop starts, the loop is called a count-controlled loop. Use a for loop. Asking the user before each iteration if it is time to end the loop is called the ask-before-iterating technique. Appropriate for a small number of iterations Use a while loop or a do-while loop.

Controlling Number of Loop Iterations For large input lists, a sentinel value can be used to signal the end of the list. The sentinel value must be different from all the other possible inputs. A negative number following a long list of nonnegative exam scores could be suitable. 90 0 10-1

Controlling Number of Loop Iterations Example: reading a list of scores followed by a sentinel value int next = keyboard.nextint(); while (next >= 0) { Process_The_Score next = keyboard.nextint(); }

Controlling Number of Loop Iterations Using a boolean variable to end the loop View BooleanDemo.java Sample screen output

for Exercise Modify ReverseWords.java so that it reads one line of text, prints the reverse order of that line, and then reads the next line etc. The program will read and reverse new lines until the user enters only a period (sentinel value) on one line.

for Exercise public class ReverseWords { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); String line = ""; boolean inputcontinues = true; } } while (inputcontinues) { System.out.print("Enter text to be reversed " + "(period ends program): "); line = keyboard.nextline(); if (!line.equals(".")) { for (int i = line.length()-1; i >= 0; i--) { System.out.print(line.charAt(i)); } System.out.println(""); } else { inputcontinues = false; } }

The break Statement in Loops A break statement can be used to end a loop immediately. The break statement ends only the innermost loop or switch statement that contains the break statement. break statements make loops more difficult to understand. Use break statements sparingly (if ever).

The break Statement in Loops Note program fragment, ending a loop with a break statement, listing 4.8

The continue Statement in Loops A continue statement Ends current loop iteration Begins the next one Text recommends avoiding use Introduce unneeded complications

Tracing Variables Tracing variables means watching the variables change while the program is running. Simply insert temporary output statements in your program to print of the values of variables of interest Or, learn to use the debugging facility that may be provided by your system.

Tracing Variables with DrJava Open WhileWithScanner.java Choose Debugger->Debug Mode A new panel is added with Stack and Thread tabs Right-click on the code sum += num; and choose Toggle Breakpoint That line now has a red background

Tracing Variables with DrJava Click on the left-right arrows to the left of the Stack tab A new panel is added with a Watches tab Type num into the Name field and hit return Type sum into the next Name field, then return Run the program and type some numbers when promted to do so The program will stop at the breakpoint and show the values of num and sum

Tracing Variables with DrJava Click the Step Over button to move to the next statement Click the Resume button to move to the next breakpoint To exit the debugger and the program, click the Reset button located on the top panel

Loop Bugs Common loop bugs Unintended infinite loops Off-by-one errors Testing equality of floating-point numbers Subtle infinite loops The loop may terminate for some input values, but not for others. For example, you can t get out of debt when the monthly penalty exceeds the monthly payment.