Loops and Iteration CS 21a: Introduction to Computing I

Slides:



Advertisements
Similar presentations
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Advertisements

Introduction to Computers and Programming Lecture 9: For Loops New York University.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
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.
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.
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.
©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.
©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.
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.
Do … while ( continue_cond ) Syntax: do { stuff you want to happen in the loop } while (continue_condition);
Introduction to Object-Oriented Programming
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 5 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.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Java Interfaces CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (see Chapter 9 of.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Repetition Statements
Slides by Evan Gallagher
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC
Lecture 7: Repeating a Known Number of Times
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Selected Topics From Chapter 6 Iteration
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.
Arrays, For loop While loop Do while loop
Looping and Repetition
MSIS 655 Advanced Business Applications Programming
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Computing Fundamentals
Suggested self-checks:
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Building Java Programs
Review of Previous Lesson
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.
Chapter 13 Conditional Repetition
Chapter 7 Repetition Statements
Chapter 3 Flow of Control Loops in Java.
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Loops and Iteration CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 6, Horstmann text)

Loops Sometimes we want to execute a statement or a group of statements repeatedly Java structures for loops: for statement while statement do-while statement Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Example applyInterest() method in BankAccount (takes an intRate parameter) public class BankAccount { double balance; ... public void applyInterest( double intRate ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Example applyInterest() method in BankAccount (takes an intRate parameter) public class BankAccount { double balance; ... public void applyInterest( double intRate ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Shorthand for: balance = balance + interest; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Example improved Let’s add attributes for interest rate and years public class BankAccount { double balance; double intRate; // interest rate on balance int years; // age of bank account public void applyInterest( ) double interest = balance*intRate/100; balance += interest; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } ... Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Example – yearly interest yearlyInterest() method in BankAccount public class BankAccount { ... public void yearlyInterest() double interest = balance*intRate/100; balance += interest; years++; System.out.println( “Interest:” + interest +”, balance is now” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Repeatedly applying interest Suppose you want to apply interest on the balance for three years public void applyThreeYearInterest( ) { double interest; interest = balance*intRate/100; balance += interest; years++; System.out.println( “Year 1 - interest:” + interest +”, balance:” + balance ); System.out.println( “Year 2 - interest:” + interest +”, balance:” + balance ); System.out.println( “Year 3 - interest:” + interest +”, balance:” + balance ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Repeated execution We want a way to indicate that the following should be executed three times: interest = balance*intRate/100; balance += interest; years++; System.out.println( “Yearly-interest:” + interest +”, balance:” + balance ); Better still, we want the following executed where i takes the value 1, 2, 3: System.out.print( “Year ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance ); Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

The for statement Syntax Notes for ( expr1; expr2; expr3 ) statement expr1: initialization or setup (e.g., i = 1 ) expr2: condition (e.g., i <= 3 ) expr3: increment (e.g., i++) statement means any valid statement in Java (including blocks) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Applying yearly interest public void applyYearlyInterest( int numYears ) { double interest; int i; for( i = 1; i <= numYears; i++) interest = balance*intRate/100; balance += interest; System.out.print( “Year ” + i + “- interest: “+ interest ); System.out.println( “, balance:” + balance ); years++; } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Another example: factorial Given an integer n, compute n! We want: result = 1*2*3*…*n; Repeated operation(s) multiply a number i to result increment the number i Do n times starting with i = 1, result = 1: result = result * i; i = i + 1; Looping code aka “Iterative” code one round of the loop is called an “iteration” Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

The while statement Setup Condition Loop Body Increment / Syntax: while ( condition ) statement Setup public int factorial( int n ) { int result = 1; int i = 1; while ( i <= n ) result = result * i; i = i + 1; } return result; Condition Loop Body Increment / Go to next step Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

The do-while Statement Syntax: do statement while ( condition ); public int factorial( int n ) { int result = 1; int i = 1; do result = result * i; i = i + 1; } while ( i <= n ); return result; } Setup Loop Body Increment / Go to next step Condition (at the end of loop) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Components of a loop Setup/Initialization Terminating/Continuing condition Incrementing step not necessarily an increment, but something that moves the program further on – i.e., to a state possibly closer to a terminating condition e.g., decrementing, dividing, multiplitying, getting another input, etc. Loop body Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Using a for loop for factorial public int factorial( int n ) { int result = 1; int i; for ( i = 1; i <= n; i++ ) result = result * i; } return result; Setup Condition Loop Body Increment / Go to next step Increment / Go to next step Increment / Go to next step Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

for loop (version 2) You can declare the “counter” variable inside the for scope is within the loop’s block good when i is not used outside of the loop public int factorial( int n ) { int result; result = 1; for ( int i = 1; i <= n; i++ ) result = result * i; } return result; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

for loop (version 3) You can have multiple statements in “setup” part of for separated by commas need to declare the variables before the for, since we can’t have declarations here also works for increment part public int result( int n ) { int i, result; for ( result = 1, i = 1; i <= n; i++ ) result = result * i; } return result; NOT RECOMMENDED! generally bad style to put several statements on one line if possible, choose a single counter variable, and just use that Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

for loop (version 3b) public int factorial( int n ) { int i, result; for ( result = 1, i = 1; i <= n; result *= i, i++ ) } return result; This is legal, but BAD! cryptic the for loop has no body! Shorthand for: result = result*i; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

for loop (version 3w) (“w” for worse!) public int factorial( int n ) { even more cryptic Some C programmers actually like writing like this! DON’T! public int factorial( int n ) { int i, result; for ( result = 1, i = 1; i <= n; result *= i++ ) } return result; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

for and while are equivalent! public int factorial( int n ) { int result; result = 1; for ( int i = 1; i <= n; i++ ) result = result * i; } return result; public int factorial( int n ) { int result; result = 1; int i = 1; while ( i <= n ) result = result * i; i++; } return result; Setup Braces here are shown because in Java (not in C), scope of vars declared in setup of for is limited Condition Increment Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Deciding which statement to use Using a for statement most appropriate when the number of iterations is known (e.g., factorial of n) Difference between while and do-while loop condition is performed at the top (while) or at the bottom (do-while) of the loop In do-while, body is executed at least once in while, we check first before executing Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Nested Loops It is possible to have a loop within a loop Example (What gets printed out?) for ( int i = 0; i < 5; i++ ) { System.out.println( i ); for ( int j = 0; j < 5; j++ ) System.out.println( j ); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Nested Loops The condition can vary depending on the outer loop Example (What gets printed out?) for ( int i = 0; i < 5; i++ ) { System.out.println( i ); for ( int j = 0; j < i; j++ ) System.out.print( j ); } System.out.println( ); Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Loop Pitfall # 1 Infinite Loops 1 int years = 0; while ( years < 20 ) { double interest = balance * rate / 100; balance = balance + interest; } 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int years = 20; while ( years > 0 ) { years++; double interest = balance * rate / 100; balance = balance + interest; } 2 Note: In theory, this while statement is an infinite loop, but in programming languages other than Java, this loop will eventually terminate because of an overflow error. An overflow error will occur if you attempt to assign a value larger than the maximum value the variable can hold. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. With Java, however, an overflow will not cause the program termination. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. examples adapted from Chapter 6 of Java Concepts by C. Horstmann Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Loop Pitfall # 2 Using Real Numbers 1 2 float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; } //seven 3s 1 Using Real Numbers Loop 2 terminates, but Loop 1 does not because a float or double is only an approximation of a real number. Operations are not necessarily exact. float count = 0.0f; while ( count != 1.0f ) { count = count + 0.33333333f; } //eight 3s 2 Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/3.0 + 1.0/3.0 + 1.0/3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision. examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Loop Pitfall – 3 Goal: Execute the loop body 10 times. 1 2 3 4 1 3 and count = 1; while ( count < 10 ) { . . . count++; } 1 count = 1; while ( count <= 10 ) { . . . count++; } 2 count = 0; while ( count <= 10 ) { . . . count++; } 3 count = 0; while ( count < 10 ) { . . . count++; } 4 Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop. 1 3 and exhibit off-by-one error (OBOE). examples and slide adapted from Introduction to Object Oriented Programming with Java by C. Thomas Wu, Copyright 2000, McGraw-Hill Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Avoiding pitfalls Infinite Loop Real Numbers loop body or increment statement should contain a statement that eventually leads to termination Real Numbers Avoid using == or != when using real numbers Use <= or >= depending on direction of loop OBOE (Off-By-One-Error) aka “Fencepost error” To execute the loop body N times … if counter starts at 0, check for counter < N if counter starts at 1, check for counter <= N Remember that after the loop, the counter (if still in scope) will be beyond the limit of your condition if we started from 0, counter would be N, if we started from 1, counter would be N+1 Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Some exercises using loops List all even numbers less than a given limit Approach 1: Use an if-statement inside a for-loop Approach 2: Arrange it so that the for-loop does skips through the odd numbers Print out all 16 pairs of numbers from the set {0,1,2,3} What if the numbers have to be distinct? What if the the order does not matter (i.e., the pair 1,2 is the same as the pair 2,1) Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Printing a shape Create a triangle pattern * ** *** Loop through rows for (int i = 1; i <= n; i++) { // make triangle row } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Printing a shape – cont. The following loop creates a row of i stars for (int j = 1; j <= i; j++) r = r + "*"; r = r + "\n"; Put loops together → Nested loops String r = "" ; for (int i = 1; i <= n; i++) { // make triangle row } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Triangle class public class Triangle { private int width; public Triangle(int aWidth) width = aWidth; } 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; Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

TriangleRunner class public class TriangleRunner { 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()); } Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved

Exercises for nested loops Create similar classes that print out these shapes as well: * * * * Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved