Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
CS0004: Introduction to Programming Repetition – Do Loops.
Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Loops – While, Do, For Repetition Statements Introduction to 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.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©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.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
New Mexico Computer Science For All More Looping in NetLogo Maureen Psaila-Dombrowski.
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.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
CS101 Computer Programming I Chapter 4 Extra Examples.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
While ( number
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Chapter 4 Repetition Statements (loops)
Loop Structures.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
3 Control Statements:.
Repetition Control Structure
3.5- The while Statement The while statement has the following syntax:
Chapter 6: Repetition Statements
A LESSON IN LOOPING What is a loop?
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Looping and Repetition
Presentation transcript:

Chapter 7 - Iteration

Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements – or loops – with the for, while, and do-while statements Learn potential pitfalls of infinite loops and off by one errors Learn potential pitfalls of infinite loops and off by one errors Understand nested loops Understand nested loops Process input Process input

Chapter 7 Control statements Control statements Already learned about selection statements Already learned about selection statements Now learn about repetition statements, or loop statements Now learn about repetition statements, or loop statements Repetition statements – repeat a block of code for a fixed number of times, or until some condition is met Repetition statements – repeat a block of code for a fixed number of times, or until some condition is met 3 types: while, do-while, and for 3 types: while, do-while, and for

While statement While statements/loops, repeat a body of code until some condition is met While statements/loops, repeat a body of code until some condition is met This is helpful for certain problems such as: This is helpful for certain problems such as: Feed cat until it is full Feed cat until it is full Drink beer until pitcher is done Drink beer until pitcher is done Get user input until they hit the Esc key Get user input until they hit the Esc key Play a game until someone wins Play a game until someone wins

While statement Syntax: while ( ) //AKA loop body //AKA loop body Similar to if statements – if the block is a single statement, curly braces are not indeed Similar to if statements – if the block is a single statement, curly braces are not indeed Normally, it is a block statement Normally, it is a block statement Keeps executing the block as long as is true Keeps executing the block as long as is true

Example Add integers 1 through 100 (1+2+…+100) Add integers 1 through 100 (1+2+…+100) int sum = 0, number = 1;//Important to //intialize while ( number <= 100 ){//boolean expression sum = sum + number; number++;// what does this do? }

if Flow Diagram condition body false true

while Flow Diagram condition body false true

Example int bottlesOfBeer = 99 while (bottlesOfBeer > 0){ System.out.println(bottlesOfBeer+” on the wall”); bottlesOfBeer--; System.out.println(“Take one down, pass it around); System.out.println(bottlesOfBeer+” on the wall”); }

Compound Balance Problem: Want to calculate how many years my balance will take to appreciate to $20,000 given I start $10,000 and have a 5% interest rate Problem: Want to calculate how many years my balance will take to appreciate to $20,000 given I start $10,000 and have a 5% interest rate

int years = 0; Scanner in = new Scanner(System.in); System.out.print (“Enter target balance: “); int targetBalance = in.nextInt(); while (balance < targetBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println(“Your target will be achieved in “+ years + “ years.”);

while (true){ <statement>} How long will this loop run? How long will this loop run? Why would we want to do this Why would we want to do this Can we stop it? Can we stop it?

Common Error 7.1 Most common mistake – loop is never terminated Most common mistake – loop is never terminated is always true is always true Infinite loop – have to close program (Ctrl+c) Infinite loop – have to close program (Ctrl+c) int count = 1; while (count != 10){ count += 2; } int product = 0; while (product < ){ product *= 5; }

Infinite loop Common cause – not advancing variable Common cause – not advancing variable int years = 0; while (years < 20){ double interest = balance * rate / 100; balance = balance + interest; } Common cause – increment vs. decrement Common cause – increment vs. decrement int years = 20; while (years > 0){ years++; double interest = balance * rate / 100; balance = balance + interest; }

Overflow Value of a variable exceeds precision Value of a variable exceeds precision short s; while (s < 3000){ s++;} double count = 0; while (count != 1.0){ count = count }

Underflow Real numbers are not always stored exactly, sometimes an approximation is needed Real numbers are not always stored exactly, sometimes an approximation is needed double count = 0; while (count != 1.0){ count = count + 1.0/3.0; }//May not work!

Off by one Another common error is to be off by one Another common error is to be off by one int count = 1; while (count < 10){ …count++;} How many executions? int count = 0; while (count <= 10){ …count++;} How many executions?

Off by one Be careful when counting Be careful when counting Analogous to logic problems Analogous to logic problems If I place a post every ten feet, how many posts do I need for a 100 ft fence? If I place a post every ten feet, how many posts do I need for a 100 ft fence?

do-while statement The second repetition statement: do-while loop/statement The second repetition statement: do-while loop/statement while loops are use pretest format, where we test the boolean expression before executing anything while loops are use pretest format, where we test the boolean expression before executing anything do-while is a posttest loop – we test the boolean after executing the loop do-while is a posttest loop – we test the boolean after executing the loop

Syntax do while ( ) OR do{ <statements> }while ( )

Do-while vs while What does this posttest vs. pretest mean What does this posttest vs. pretest mean A while loop body is not guaranteed to execute A while loop body is not guaranteed to execute while (false){…} do-while body is guaranteed to execute at least once do-while body is guaranteed to execute at least once

while Flow Diagram condition body false true

do - while Flow Diagram condition body true false

Example int sum = 0, number = 1; do{ sum += number; number++; } while (sum <= ); //Sums all numbers 1 through 1,000,000

int count = 11; do { System.out.println(count); count = count + 1; } while (count < 5);

Input double value; do{ System.out.println(“Enter a positive number: “); value = in.nextInt(); } while (value <= 0);

While version Could use a flag – boolean control variable Could use a flag – boolean control variable double value; boolean done = false; while (!done) { System.out.println(“Enter a positive number: “); value = in.nextInt(); if(value > 0) done = true; }

Avoid Repeat Code count = 0; do{ System.out.print(“Enter score: “); score = in.nextInt(); count++; if (count >= 20){ System.out.println(“Can’t take more scores”); } else if (score < 0){ System.out.println(“Invalid score”); } else if (score == 0){ System.out.println(“User chooses to exit”); } } while ( !(count >= 20 || score == 0 || score = 20 || score == 0 || score < 0 )

count = 0; boolean repeat = true; do{ System.out.print(“Enter score: “); score = in.nextInt(); count++; if (count >= 20){ System.out.println(“Can’t take any more scores”); repeat = false; repeat = false; } else if (score < 0){ System.out.println(“Invalid score”); repeat = false; repeat = false; } else if (score == 0){ System.out.println(“User chooses to exit”); repeat = false; repeat = false;} } while ( repeat )//Easier to understand

7.2 for loop Most common loop, mainly for count- controlled loops Most common loop, mainly for count- controlled loops for(i = start; i <= end; i++) {...}

Syntax for ( ; ; ) OR for ( ; ; ){ <statements>} Initialization occurs only the first time the loop is executed, Initialization occurs only the first time the loop is executed, boolean expression is tested before every loop boolean expression is tested before every loop The increment operator is applied at the end of each loop The increment operator is applied at the end of each loop

for Flow Diagram test condition body true false increment initialization

Sum problem Saw it in while and do-while, here it is in for Saw it in while and do-while, here it is in for int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } i is a control variable, keeps track of number of repititions i is a control variable, keeps track of number of repititions

Interest Problem for(int i = 1; i <= n; i++) { double interest = balance * rate/100; balance = balance + interest; }

Sum problem int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } i is set to 1 the first time the loop is executed i is set to 1 the first time the loop is executed Before executing each time, check to see that i<=100 (like in while loop) Before executing each time, check to see that i<=100 (like in while loop) Add 1 to i at the end of each cycle Add 1 to i at the end of each cycle

Initialization int sum = 0; for ( int i = 1 ; i <=100; i++){ sum += i; //equivalent to sum = sum + 1; } We can also declare i in the initialization, but i will be local to the for loop and not available outside We can also declare i in the initialization, but i will be local to the for loop and not available outside Usually not an issue Usually not an issue Can also leave initialization blank Can also leave initialization blank

Boolean Expression int sum = 0; for (int i = 1; i <=100 && sum < 1111 ; i++){ sum += i; //equivalent to sum = sum + 1; } Can test multiple conditions in boolean expression Can test multiple conditions in boolean expression Is this still count controlled? Is this still count controlled?

Update int sum = 0; for (int i = 1; i <=100 && sum < 1111; i += 2 ){ sum += i; //equivalent to sum = sum + 1; } Can have any formula for incrementing Can have any formula for incrementing Add only odd integers Add only odd integers Decrease by 1, i-- Decrease by 1, i--

int sum = 0, number = 1; do{ sum += number; number++; }while ( number <= 100) int sum = 0, number = 1; while ( number <= 100 ){ sum = sum + number; number++;} int i, sum = 0; for (i = 1; i <=100; i++){ sum += i; }

Legal for loops For loops can have many formats that are legal For loops can have many formats that are legal for(int i =0; i <= 100; sum += i++); for(;;i++){…} for(System.out.println(“Inputs: “); (x = in.nextDouble()) > 0; sum += x) count++;

Scope Is this legal? for(int i = 0; i < 100; i++){ …}System.out.println(i); What if you want to know the value of i after loop is done

Is this legal? for(int i = 0; i <= 10; i++) System.out.println(i * i); for(int i = 0; i <= 10; i++) System.out.println(i * i * i); for(int i = 0, j = 10; i <= 10; i++, j--) System.out.println(i * i * i);

7.4 Nested loops Recall from if-statements, any type of statement can be placed in the blocks or body Recall from if-statements, any type of statement can be placed in the blocks or body In for loops, we can put an if statement, while loop, do-while loop, etc. inside the body In for loops, we can put an if statement, while loop, do-while loop, etc. inside the body Very common to have another for loop inside – a nested-for statement Very common to have another for loop inside – a nested-for statement

Mult. Table for (int i = 0; i <= 10; i++){ for (int j = 0; j <= 10; j++){ result = i * j; System.out.print(“ “ + result); }System.out.println(“”);} What will this output? What will this output? What order will output in? What order will output in? How many times does each loop execute? How many times does each loop execute?

Practice Write a loop to output the following pattern Write a loop to output the following pattern* * * * * * * * * * … n rows

Practice Do more code for the following Do more code for the following* * * * * * * * * Given h, where h=3 above

Practice Given N Given N Calculate ½ + 2/3 + ¾ +…+N-1/N Calculate ½ + 2/3 + ¾ +…+N-1/N

7.4 Sentinel Values Add integers 1 through 100 (1+2+…+100) Add integers 1 through 100 (1+2+…+100) int sum = 0, number = 1;//Important to //intialize while ( number <= 100 ){//boolean expression sum = sum + number; number++;// what does this do? } Count controlled – the body is executed a fixed number of times Count controlled – the body is executed a fixed number of times

Sentinel-controlled loop – executed repeatedly until a sentinel(designated value) is encountered Sentinel-controlled loop – executed repeatedly until a sentinel(designated value) is encountered Sentinel value: Can be used for indicating the end of a data set Sentinel value: Can be used for indicating the end of a data set 0 or -1 make poor sentinels; better use a meaningful value (‘Q’ for quit) 0 or -1 make poor sentinels; better use a meaningful value (‘Q’ for quit)

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);... } How do we make this a loop?

Loop and a half boolean done = false; while(!done){ System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")){ done = true; } else { double x = Double.parseDouble(input);... }}

Tips Symmetric vs. Asymmetric Symmetric vs. Asymmetric for(int i = 1; i <= n; i++) for(int i = 0; i < str.length(); i++) Counting iterations Counting iterations for(int i = a; i <= b; i++) How many executions?

Alternatives to loop and a half Can be confusing to read Can be confusing to read 2 alternatives: test input in condition, or use break 2 alternatives: test input in condition, or use break while(!(input = in.next()).equalsIgnoreCase(“Q”)){ Process data }

break boolean done = false; while(!done){ System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")){ break; } else { double x = Double.parseDouble(input);... }}

Code jumps break – exits loop break – exits loop Will immediately exit, just like for switch Will immediately exit, just like for switch continue – will skip the rest of the statements in the loop and start next iteration of the loop continue – will skip the rest of the statements in the loop and start next iteration of the loop

Spaghetti Code Many programmers avoid using these various jump statements Many programmers avoid using these various jump statements break, continue, goto break, continue, goto Can cause confusing code that often leads to harmful bugs Can cause confusing code that often leads to harmful bugs

Which to choose? Count controlled Count controlled for loops usually best for loops usually best Sentinel based loops Sentinel based loops while loops usually beset while loops usually beset What about do-while? What about do-while? Priming reads, although can use a flag instead with while Priming reads, although can use a flag instead with while

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

Sequence If producing a random sequence, the sequence will be different every time If producing a random sequence, the sequence will be different every time Note: Not truly random (psuedorandom) Note: Not truly random (psuedorandom) Formula used, but uses complicated factors to make it seem Random Formula used, but uses complicated factors to make it seem Random

How do you use a random number generator to simulate the toss of a coin? How do you use a random number generator to simulate the toss of a coin? How do we get a double between 0.0 and 5.0? 0.5 and 2.0? How do we get a double between 0.0 and 5.0? 0.5 and 2.0? How do we choose a random coordinate on a grid? How do we choose a random coordinate on a grid?

Loop Invariant Loop invariant – a condition that is always true (beginning, after each iteration, and at the end) Loop invariant – a condition that is always true (beginning, after each iteration, and at the end) Ex. Loop invariant: r*b i = a n Ex. Loop invariant: r*b i = a n double r = 1, b = a; int i = n; while(i > 0){ if(i%2 == 0){ b = b*b; i = i-2; } else { r = r*b; i--;}}