 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.

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
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.
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.
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.
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.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Loops III Lecture 19, Wed Mar
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
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.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Lecture 4 Loops.
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
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.
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.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 6 – Iteration.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Repetition Statements while and do while loops
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CS110 Programming Language I Lab 4: Control Statements I Computer Science Department Spring 2014.
If Statement if (amount
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.
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.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 7 - Iteration.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
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 Six: Iteration
Chapter Goals To implement while, for, and do loops
Chapter 6 – Loops.
Selected Topics From Chapter 6 Iteration
LOOPS.
Chapter Six - Iteration
LRobot Game.
Chapter 7 Iteration.
Lecture Notes – Week 2 Lecture-2
while while (condition) { statements }
Repetition Statements
Building Java Programs
Announcements Lab 3 was due today Assignment 2 due next Wednesday
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
Loops and Iteration CS 21a: Introduction to Computing I
Looping and Repetition
Presentation transcript:

 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 statements delimited by { } ) while (condition) statement;

 Invest $10,000, 5% interest, compounded annually YearBalance 0$10,000 1$10,500 2$11,025 3$11, $12, $12,762.82

 When has the bank account reached a particular balance? while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; }

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

.  Loops run forever–must kill program 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; }

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 <= ?

 Executes loop body at least once:  Example: Validate input  Alternative: boolean done = false; while (!done) { System.out.print("Please enter a positive number: "); value = in.nextDouble(); if (value > 0) done = true; } do statement while (condition); double value; do { System.out.print("Please enter a positive number: "); value = in.nextDouble(); } while (value <= 0); Continued…

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

 Example: for (initialization; condition; update) statement for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } Continued…

 Equivalent to  Other examples: initialization; while (condition) { statement; update; } for (years = n; years > 0; years--)... for (x = -10; x <= 10; x = x + 0.5)...

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

 A semicolon that shouldn't be there  A missing semicolon sum = 0; for (i = 1; i <= 10; i++); sum = sum + i; System.out.println(sum); for (years = 1; (balance = balance + balance * rate / 100) < targetBalance; years++) System.out.println(years);

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

 Make triangle row is another loop  Put loops together → Nested loops for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n";

01: /** 02: This class describes triangle objects that can be 03: displayed as shapes like this: 04: [] 05: [][] 06: [][][] 07: */ 08: public class Triangle 09: { 10: /** 11: Constructs a triangle. aWidth the number of [] in the last row of the triangle. 13: */ 14: public Triangle(int aWidth) 15: { 16: width = aWidth; 17: } 18: Continued…

19: /** 20: Computes a string representing the triangle. a string consisting of [] and newline characters 22: */ 23: public String toString() 24: { 25: String r = ""; 26: for (int i = 1; i <= width; i++) 27: { 28: // Make triangle row 29: for (int j = 1; j <= i; j++) 30: r = r + "[]"; 31: r = r + "\n"; 32: } 33: return r; 34: } 35: 36: private int width; 37: }

01: /** 02: This program tests the Triangle class. 03: */ 04: public class TriangleTester 05: { 06: public static void main(String[] args) 07: { 08: Triangle small = new Triangle(3); 09: System.out.println(small.toString()); 10: 11: Triangle large = new Triangle(15); 12: System.out.println(large.toString()); 13: } 14: }

[] [][] [][][] [] [][] [][][] [][][][] [][][][][] [][][][][][] [][][][][][][] [][][][][][][][] [][][][][][][][][] [][][][][][][][][][] [][][][][][][][][][][] [][][][][][][][][][][][] [][][][][][][][][][][][][] [][][][][][][][][][][][][][] [][][][][][][][][][][][][][][]

5. What is the value of n after the following nested loops? int n = 0; for (int i = 1; i <= 5; i++) for (int j = 0; j < i; j++) n = n + j;

5. 20

 Sentinel value: Can be used for indicating the end of a data set  0 or -1 make poor sentinels; better use Q System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")) We are done else { double x = Double.parseDouble(input);... }

 Sometimes termination condition of a loop can only be evaluated in the middle of the loop  Then, introduce a boolean variable to control the loop: boolean done = false; while (!done) { Print prompt String input = read input; if (end of input indicated) done = true; else { // Process input } }

 In a simulation, you repeatedly generate random numbers and use them to simulate an activity  Random number generator  Throw die (random number between 1 and 6) Random generator = new Random(); int n = generator.nextInt(a); // 0 <= n < a double x = generator.nextDouble(); // 0 <= x < 1 int d = 1 + generator.nextInt(6);

 Problem 6.1, page 278  Currency converter between US dollars, Euros, Indian rupees, British pounds, Chinese Yuan, … Pick at least 3 currencies to convert between. Continue prompting user for currency and amount to convert until Q is entered  Problem 6.13, page 283  Graphical simulation of a random walk in a 20x20 grid