Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block.

Slides:



Advertisements
Similar presentations
Computer Science A 4 13/3. 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.
Advertisements

More loops Horstmann Ch 7 continued.. The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition?
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
Introducing Loop Statements Liang, pages Loop statements control repeated execution of a block of statements Each time the statements in the block.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
More loops Linag, Chpt 3, pp The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition? loop-body.
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.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
Datalogi A 5: 6/10. while Loops Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement; Most.
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.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
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
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson 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 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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 6 Chapter.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 6 - Loops.
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 6 - Loops.
 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 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 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 6 – Iteration.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
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:
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.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
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.
Slides by Evan Gallagher
Slides by Evan Gallagher
Java Fundamentals 4.
Chapter Goals To implement while, for, and do loops
Chapter 5: Control Structures II
Repetition-Counter control Loop
Selected Topics From Chapter 6 Iteration
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Outline Altering flow of control Boolean expressions
Chapter Six - Iteration
Chapter 7 Iteration.
Control Statements Loops.
Control Statements Loops.
Building Java Programs
Building Java Programs
6.2 for Loops Example: for ( int i = 1; i
Building Java Programs
Presentation transcript:

Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block are carried out, we speak of one iteration of the loop

Structure of a Loop 1.Evaluate the continue-condition (a.k.a. the loop guard) 2.If the continue-condition is true, execute the loop body and go back to 1 3.If the continue-condition is false, skip the loop body entirely and continue with the next line of code

The WHILE loop continue- condition? loop-body statements next statement false true while (i < 100) { System.out.print("."); i++; }

Printing 100 dots int i = 0; while (i < 100) { System.out.print("."); i++; } i < 100? print dot i++ next statement false true

Another example int count = 1; while (count != 100) { System.out.print(count + " "); count++; } Output:

Counting backwards int count = 100; while (count != 0) { System.out.print(count + " "); count--; } Output:

Add up some integers 1.Set 'sum' to zero 2.Read in an integer (from JOptionPane; convert to int using Integer.parseInt() 3.While 'data' is not zero.. 1.Add 'data' to 'sum'; 2.Read in another integer into 'data' 4. Print out the value of 'sum'

Adding program 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);

What is wrong with this loop? int count = 0; while (count != 99) { System.out.print(count + " "); count = count + 2; }

Calculating the Growth of an Investment Invest $10,000, 5% interest, compounded annually YearBalance 0$10,000 1$10,500 2$11,025 3$11, $12, $12,762.82

Growth of an investment How many years will it take a bank account reached a particular balance? while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; }

Stand-alone growth program class GrowBalance { public static void main(String[] args){ double rate = 3.0; double balance = 500.0; double targetBalance = double year = 0; while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; System.out.println(“year ”+year+ “: balance ”+balance); }

Object-based investment growth public class Investment{ private double balance; private double rate; private int years; public Investment(double aBalance, double aRate) { balance = aBalance; rate = aRate; years = 0; } public void waitForBalance(double targetBalance) { while (balance < targetBalance){ years++; double interest = balance * rate / 100; balance = balance + interest; } public int getYears() { return years; } public double getBalance(){ return balance; } }

Test program to create investment objects public class InvestmentTester { public static void main(String[] args) { final double INITIAL_BALANCE = 10000; final double RATE = 5; Investment invest = new Investment(INITIAL_BALANCE, RATE); invest.waitForBalance(2 * INITIAL_BALANCE); int years = invest.getYears(); System.out.println("The investment doubled after " + years + " years"); }

Sequence processing Many tasks require the program to process a series of numbers. Question: how do we know when to stop? Answer 1: know in advance how long the sequence is... Answer 2: provide a sentinel value to signal the end...

Sample problems 1) Write a Java program that reads a sequence of positive integer values, terminated by a -1, and calculate their average. 2) Modify your program so that it reads in 5 and only 5 numbers and then calculates their average.

Developing a WHILE loop 1.Decide on a loop guard. The loop will terminate when this guard is false. 2.Set up initial conditions for loop. E.g. make sure variables in the guard are initialized. 3.Write the 'work' part of the loop body 4.Write the 'change' part of the loop body. This must potentially alter the value of the guard.

Things we know for certain 1.Before the loop: anything could be true 2.At the start of the loop body: the guard is guaranteed to be true 3.Immediately after the loop body: the guard is guaranteed to be false

Basic sequence operations Reduction. E.g. finding the average of a sequence Mapping: E.g. printing the square of each member of a sequence Filtering: E.g. doing something only with certain sequence elements

Doing it all at once Problem: Write a program which reads a sequence of positive integer values, terminated by -1, and prints the average of the square of the odd elements of the sequence. 1.Find the odd elements (filtering) 2.Compute their squares (mapping) 3.Calculate the average (reduction)