More loops Horstmann Ch 7 continued.. The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition?

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Chapter 6 Iteration Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Introducing Loop Statements Liang, pages Loop statements control repeated execution of a block of statements Each time the statements in the block.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
More loops Linag, Chpt 3, pp The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition? loop-body.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Chapter 6  Iteration 1 Chapter 6 Iteration. Chapter 6  Iteration 2 Chapter Goals  To be able to program loops with while and for (sometimes do ) statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Loops III Lecture 19, Wed Mar
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Objectives You should be able to describe:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 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.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Java Programming: From the Ground Up
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Sahar Mosleh California State University San MarcosPage 1 Program Control Statement.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Computer Programming1 Computer Science 1 Computer Programming.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Chapter 5: Control Structures II
Repetition-Counter control Loop
Counted Loops.
Lecture 07 More Repetition Richard Gesick.
Selected Topics From Chapter 6 Iteration
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Outline Altering flow of control Boolean expressions
Chapter 7 Iteration.
Repetition Statements
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.
Loops CGS3416 Spring 2019 Lecture 7.
Loops and Iteration CS 21a: Introduction to Computing I
Presentation transcript:

More loops Horstmann Ch 7 continued.

The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition? loop-body statements next statement false true DO-LOOP

Using a do-loop Use this form when you want the loop body to be executed at least once int data; int sum = 0; String dataString; do { dataString = JOptionPane.showInputDialog(null,”enter number:”); data = Integer.parseInt(dataString); sum += data; } while (data != 0); JOptionPane.showMessageDialog(null,”Numbers sum to ”+sum);

Things to know about do-loops The loop body will always be executed one The first execution is done before the guard is checked The do-loop is nothing more than a small variant of the while-loop It is often useful for checking user input

When to use the do-loop? int sum; int data; String dataString; dataString=JOptionPane.showInputDialog(null,”enter number:”); data = Integer.parseInt(dataString); while(data != 0) { dataString = JOptionPane.showInputMessage(null,”enter number:”); data = Integer.parseInt(dataString); sum = sum + data; //could have used: sum += data; } JOptionPane.showMessageDialog(null,”Numbers sum to ”+sum);

A better way int data; int sum = 0; String dataString; do { dataString=JOptionPane.showInputDialog(null,”enter number:”); data = Integer.parseInt(dataString); sum += data; } while (data != 0); JOptionPane.showMessageDialog(null,”Numbers sum to ”+sum); We don’t have to get the first piece of data, add it to the sum variable, and then start the loop.

The for-loop The for-loop is another variant of the while loop Every for-loop can be written as a while loop Not every while-loop can be written as a for-loop Use a for-loop when you know exactly how many times the loop body should be executed

The for loop: Three things in one line for ( ; ; ) {... } 1.Initialization: (declare and) set a counter, to 0. This is done before everything else. 2.Guard: loop ends when this is false. This is tested before each pass through the loop. 3.Adjustment: e.g. increment a counter. This is done at the end of each pass through the loop.

Examples for (int i=0; i<10; i++) { JOptionPane.showMessageDialog(null, “ ”+i); } int i; for (i=10; i>0; i--) { JOptionPane.showMessageDialog(null, “ ”+i); }

From while to for int i = startValue; while (i < endValue) {..... i++; } for (int i=startValue; i<endValue; i++) {... }

Flow of control in a for-loop initialization test guard loop bodynext statement adjust true false

Rules and guidelines for “for” Counters can be declared and initialized in one go Never (never) change the value of the counter inside the loop body I mean it. Never do that! If the loop body is one statement only, you can omit the braces—but please don’t! Indent the code within the loop body..

Examples // Compute sum = … + 1;... double sum = 0; // Keep adding 0.01 to sum for (double i=0.01; i <= 1.0 ; i = i+0.01) { sum += i; } JOptionPane.showMessageDialog("The sum is " + sum);

Common error The 3 elements of the for-loop header are sparated by semi-colons, not commas! Do this: for (int i=0; i<10; i++) Not this: for (int i=0, i<10, i++) Keep your loops as simple as possible

Nesting for-loops Inside the loop body of a for-loop, we can put another for-loop Each time through the 1 st for-loop, we execute the 2 nd loop until its guard is false Handy for printing tables like this:

Simple example for (int i=0; i<5; i++) { for (int j=0; j<3; j++) { System.out.print(i+“ ”); } System.out.println(); }

Nested Loops Create triangle pattern Loop through rows [] [][] [][][] [][][][] for (int i = 1; i <= n; i++) { // make triangle row }

for (int i = 1; i <= n; i++) { // make triangle row } for (int i = 1; i <= n; i++){ for (int j = 1; j <= i; j++) { r = r + "[]"; } r = r + "\n"; } Nested Loops Make triangle row is another loop Put one loop inside the other → Nested loops for (int j = 1; j <= i; j++) { r = r + "[]"; } r = r + "\n"; \\ “\n” means end of line

/** This class describes triangle objects that can be displayed with printed shapes */ public class Triangle{ private int width; /** Constructs a aWidth number of [] in the last row of triangle. */ public Triangle(int aWidth){ width = aWidth; } /** Computes a string representing the a string consisting of [] and newline characters */ public String toString(){ String r = ""; for (int i = 1; i <= width; i++){ for (int j = 1; j <= i; j++) { r = r + "[]"; } r = r + "\n"; } return r; }

File TriangleTester.java /** This program tests the Triangle class. */ public class TriangleTester{ public static void main(String[] args){ Triangle small = new Triangle(3); System.out.println(small.toString()); Triangle large = new Triangle(15); System.out.println(large.toString()); }

break-ing out of a loop Inside a loop body, the statement break; causes execution to leave the loop immediately. This is usually unnecessary, and shows that not enough though has gone into the development of a guard.

Example of break int sum = 0; int item = 0; while (item < 5) { item ++; sum += item; if (sum >= 6) break; } System.out.println("The sum is " + sum);

continue This keyword also stops interation of the loop body But...the program then starts the next iteration of the loop (testing the loop guard first) This is also usually unnecessary, and can be replaced by an if-statement.

Example of continue int sum = 0; int item = 0; while (item < 5) { item++; if (item == 2) continue; sum += item; } System.out.println("The sum is " + sum);

Object-oriented approach to averages /** Computes the average of a set of data values. */ public class DataSet{ private double sum; private double maximum; private int count; /** Constructs an empty data set. */ public DataSet(){ sum = 0; count = 0; maximum = 0; } /** Adds a data value to the data x a data value */ public void add(double x){ sum = sum + x; if (count == 0 || maximum < x) { maximum = x; } count++; }

(continued) public double getAverage(){ if (count == 0) { return 0; } else { return sum / count; } } public double getMaximum(){ return maximum; } } // close the DataSet class Public class DataSestTester{ public static void main(String[] args){ DataSet myData = new DataSet(); String input; do { input = JOptionPane.showInputDialog(null, “number?”); myData.add(Double.parseDouble(input) ); } while(input.length() > 0); JOptionPane.showMessageDialog(null,“the average of those numbers is ”+ myData.getAverage() ); System.exit(0); }}