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.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS0004: Introduction to Programming Repetition – Do Loops.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Computer Science 1620 Loops.
Random Number Generation public class Hand { private int card1; private int card2; private int card3; private Random rand; public static final int NO_CARD.
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.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
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.
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.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
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,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
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 © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 6 - Loops.
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.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
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.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Java Prepared by Gary Langner Types of Loops u for loop (entrance controlled) –do an action for a definite number of times u while loop (entrance controlled.
If Statement if (amount
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
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 © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
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.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
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.
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.
Sophomore Scholars Java
Slides by Evan Gallagher
Slides by Evan Gallagher
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter Six: Iteration
Chapter Goals To implement while, for, and do loops
Chapter 5: Control Structures II
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Repetition-Counter control Loop
Selected Topics From Chapter 6 Iteration
LOOPS.
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
LESSON 11 – WHILE LOOPS UNIT 5 – 1/10/17.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Chapter Six - Iteration
Chapter 7 Iteration.
Chapter 6: Repetition Statements
Repetition Statements (Loops) - 2
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.
6.2 for Loops Example: for ( int i = 1; i
Presentation transcript:

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 nested loops To learn how to process input To implement simulations Chapter Goals

Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement Most commonly, the statement is a block statement (set of statements delimited by { } ) while Loops

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

When has the bank account reached a particular balance? while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } Calculating the Growth of an Investment

01: /** 02: A class to monitor the growth of an investment that 03: accumulates interest at a fixed annual rate. 04: */ 05: public class Investment 06: { 07: /** 08: Constructs an Investment object from a starting balance and 09: interest rate. aBalance the starting balance aRate the interest rate in percent 12: */ 13: public Investment(double aBalance, double aRate) 14: { 15: balance = aBalance; 16: rate = aRate; 17: years = 0; 18: } 19: 20: /** 21: Keeps accumulating interest until a target balance has 22: been reached. targetBalance the desired balance 24: */ ch06/invest1/Investment.java

25: public void waitForBalance(double targetBalance) 26: { 27: while (balance < targetBalance) 28: { 29: years++; 30: double interest = balance * rate / 100; 31: balance = balance + interest; 32: } 33: } 34: 35: /** 36: Gets the current investment balance. the current balance 38: */ 39: public double getBalance() 40: { 41: return balance; 42: } 43: 44: /** 45: Gets the number of years this investment has accumulated 46: interest. ch06/invest1/Investment.java (cont.)

the number of years since the start of the investment 48: */ 49: public int getYears() 50: { 51: return years; 52: } 53: 54: private double balance; 55: private double rate; 56: private int years; 57: } ch06/invest1/Investment.java (cont.)

01: /** 02: This program computes how long it takes for an investment 03: to double. 04: */ 05: public class InvestmentRunner 06: { 07: public static void main(String[] args) 08: { 09: final double INITIAL_BALANCE = 10000; 10: final double RATE = 5; 11: Investment invest = new Investment(INITIAL_BALANCE, RATE); 12: invest.waitForBalance(2 * INITIAL_BALANCE); 13: int years = invest.getYears(); 14: System.out.println("The investment doubled after " 15: + years + " years"); 16: } 17: } ch06/invest1/InvestmentRunner.java Output: The investment doubled after 15 years

while Loop Flowchart

while (condition) statement Example: while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } Purpose: To repeatedly execute a statement as long as a condition is true. Syntax 6.1 The while Statement

How often is the statement in the loop while (false) statement; executed? Answer: Never. Self Check 6.1

What would happen if RATE was set to 0 in the main method of the InvestmentRunner program? Answer: The waitForBalance method would never return due to an infinite loop. Self Check 6.2

int years = 0; while (years < 20) { double interest = balance * rate / 100; balance = balance + interest; } int years = 20; while (years > 0) { years++; // Oops, should have been years–- double interest = balance * rate / 100; balance = balance + interest; } Both of these loops would run forever – must kill program Common Error: Infinite Loops

int years = 0; while (balance < 2 * initialBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("The investment reached the target after " + years + " years."); Should years start at 0 or 1? Should the test be < or <= ? Common Error: Off-by-One Errors

Look at a scenario with simple values: initial balance: $100 interest rate: 50% after year 1, the balance is $150 after year 2 it is $225, or over $200 so the investment doubled after 2 years the loop executed two times, incrementing years each time Therefore: years must start at 0, not at 1. interest rate: 100% after one year: balance is 2 * initialBalance loop should stop Therefore: must use < Think, don't compile and try at random Avoiding Off-by-One Error

Executes loop body at least once: do statement while (condition); Example: Validate input double value; do { System.out.print("Please enter a positive number: "); value = in.nextDouble(); } while (value <= 0); do Loops Continued

Alternative: boolean done = false; while (!done) { System.out.print("Please enter a positive number: "); value = in.nextDouble(); if (value > 0) done = true; } do Loops (cont.)

do Loop Flowchart

Spaghetti Code In the early days of programming it was typical to create programs with control flow like this. Such a flow chart cannot be turned into simple loop statements. Instead the goto command was necessary to jump around in your code. This style of code is known as “spaghetti code” and is not supported by modern languages such as Java.

The following sort of while loop is quite common: initialization; while (condition) { statement; update; } The for loop provides a more streamlined way of achieving this: for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } for Loops Continued

for Loop Flowchart

Other examples: for (years = n; years > 0; years--)... for (x = -10; x <= 10; x = x + 0.5)... for Loops (cont.)

for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } Purpose: To execute an initialization, then keep executing a statement and updating an expression while a condition is true. Syntax 6.2 The for Statement

01: /** 02: A class to monitor the growth of an investment that 03: accumulates interest at a fixed annual rate 04: */ 05: public class Investment 06: { 07: /** 08: Constructs an Investment object from a starting balance and 09: interest rate. aBalance the starting balance aRate the interest rate in percent 12: */ 13: public Investment(double aBalance, double aRate) 14: { 15: balance = aBalance; 16: rate = aRate; 17: years = 0; 18: } 19: 20: /** 21: Keeps accumulating interest until a target balance has 22: been reached. targetBalance the desired balance 24: */ ch06/invest2/Investment.java

25: public void waitForBalance(double targetBalance) 26: { 27: while (balance < targetBalance) 28: { 29: years++; 30: double interest = balance * rate / 100; 31: balance = balance + interest; 32: } 33: } 34: 35: /** 36: Keeps accumulating interest for a given number of years. n the number of years 38: */ 39: public void waitYears(int n) 40: { 41: for (int i = 1; i <= n; i++) 42: { 43: double interest = balance * rate / 100; 44: balance = balance + interest; 45: } 46: years = years + n; 47: } ch06/invest2/Investment.java (cont.)

49: /** 50: Gets the current investment balance. the current balance 52: */ 53: public double getBalance() 54: { 55: return balance; 56: } 57: 58: /** 59: Gets the number of years this investment has accumulated 60: interest. the number of years since the start of the investment 62: */ 63: public int getYears() 64: { 65: return years; 66: } 67: 68: private double balance; 69: private double rate; 70: private int years; 71: } ch06/invest2/Investment.java (cont.)

01: /** 02: This program computes how much an investment grows in 03: a given number of years. 04: */ 05: public class InvestmentRunner 06: { 07: public static void main(String[] args) 08: { 09: final double INITIAL_BALANCE = 10000; 10: final double RATE = 5; 11: final int YEARS = 20; 12: Investment invest = new Investment(INITIAL_BALANCE, RATE); 13: invest.waitYears(YEARS); 14: double balance = invest.getBalance(); 15: System.out.printf("The balance after %d years is %.2f\n", 16: YEARS, balance); 17: } 18: } Output: The balance after 20 years is ch06/invest2/InvestmentRunner.java

Rewrite the for loop in the waitYears method as a while loop. Answer: int i = 1; while (i <= n) { double interest = balance * rate / 100; balance = balance + interest; i++; } Self Check 6.3

How many times does the following for loop execute? for (i = 0; i <= 10; i++) System.out.println(i * i); Answer: 11 times. How about this loop? for (i = 3; i < 6; i++) System.out.println(i * i); Answer: 3 times. If the counter variable starts at counter_first and ends at counter_last and increments by one each time, the number of times the loop executes is: loops = counter_last – counter_first + 1 Counting Iterations

The following code puts all of the loop’s work into the for statement itself: for (years = 1; (balance = balance + balance * rate / 100) < targetBalance; years++) System.out.println(years); However, this loop will print years for every iteration. It should be replaced by one of the following: for (years = 1; (balance = balance + balance * rate / 100) < targetBalance; years++) ; System.out.println(years); for (years = 1; (balance = balance + balance * rate / 100) < targetBalance; years++) { } System.out.println(years); Common Errors: Semicolons

What is the problem with this code: sum = 0; for (i = 1; i <= 10; i++); sum = sum + i; System.out.println(sum); The level of indentation suggests that X belongs within the for loop. However, the semicolon terminates the loop. Java doesn’t care about indentation! Common Errors: Semicolons