Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester, 2013-2014.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
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.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
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
©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 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.
Java Programming: From the Ground Up
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Loops and Iteration for Statements, while Statements and do-while Statements.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
 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.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
The for loop.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
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)
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
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.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC
Loop Structures.
Week 4 – Repetition Structures / Loops
Java Programming: Guided Learning with Early Objects
Selected Topics From Chapter 6 Iteration
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Building Java Programs
Computer programming Lecture 3.
Building Java Programs
Suggested self-checks:
Repetition Statements
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.
Loops and Iteration CS 21a: Introduction to Computing I
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,

What’s a Loop? ► A way to express a constant number of repetitions ► A way to express an arbitrary number of repetitions, usually based on some input value or condition

Loops ► Java structures for loops: ► for statement ► while statement ► do-while statement

Example: Compound Interest public class BankAccount {... public void yearlyInterest() { double interest = balance*intRate/100; balance += interest; years++; println( "Interest:" + interest + ", balance is now" + balance ); }... }

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++; println( "Year 1 - interest:" + interest + ", balance:" + balance ); interest = balance*intRate/100; balance += interest; years++; println( "Year 2 - interest:" + interest + ", balance:" + balance ); interest = balance*intRate/100; balance += interest; years++; println( "Year 3 - interest:" + interest + ", balance:" + balance ); }

Repeated Execution

The Power of Loops ► Allow an arbitrarily long process to be described with a short algorithm

The for Statement ► Syntax for ( expr1; expr2; expr3 ) statement ► Notes ► 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)

Applying Yearly Interest 3 Times public void applyThreeYearInterest( ) { double interest; int i; for( i = 1; i <= 3; i++) { interest = balance*intRate/100; balance += interest; print( "Year " + i + "- interest: " + interest ); println( ", balance:" + balance ); years++; }

First Use of Loops ► Express a repetitive process, where the number of repetitions is constant. ► Problem can still be solved without loops, but coding is too tedious without it. ► Becomes more useful as the constant grows larger.

Applying Yearly Interest An Arbitrary Number of Times public void applyYearlyInterest( int numYears ) { double interest; int i; for( i = 1; i <= numYears; i++) { interest = balance*intRate/100; balance += interest; print( "Year " + i + "- interest: " + interest ); println( ", balance:" + balance ); years++; }

Second (More Important) Use of Loops

Practice Programming Problem

public int factorial( int n ) { int result = 1; int i = 1; while ( i <= n ) { result = result * i; i = i + 1; } return result; } The while Statement ► Syntax while ( condition ) statement Setup Condition Loop Body Increment / go to next step

public int factorial( int n ) { int result = 1; int i = 1; do { result = result * i; i = i + 1; } while ( i <= n ); return result; } The do-while Statement ► Syntax do statement while ( condition ); Setup Loop Body Increment / go to next step Condition

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

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

for Loop (version 2) public int factorial( int n ) { int result; result = 1; for ( int i = 1; i <= n; i++ ) { result = result * i; } return result; } You can declare the "counter" variable inside the for  scope is within the loop's block  good when i is not used outside the loop

for Loop (version 3) public int result( int n ) { int i, result; for ( result = 1, i = 1; i <= n; i++ ) { result = result * i; } return result; } You can have multiple statements in the "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 the increment part NOT RECOMMENDED!  generally bad style to put several statements on one line  if possible, choose a single counter variable, and just use that

for Loop (version 3b) public int factorial( int n ) { int i, result; for ( result = 1, i = 1; i <= n; result *= i, i++ ) { } return result; } Shorthand for: result = result * i; This is legal, but BAD!  cryptic  The for loop has no body!

for Loop (version 3w) public int factorial( int n ) { int i, result; for ( result = 1, i = 1; i <= n; result *= i++ ) { } return result; } ("w" for worse!)  even more cryptic  Some C programmers actually like writing like this!  DON'T!

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; } Increment Setup Condition Braces here are shown because in Java (not in C), scope of variables declared in setup of for is limited

Deciding which Statement to Use ► Using a for statement ► most appropriate when the number of iterations is easily known (e.g., factorial) ► 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

Practice Programming Problem ► Write a program that reads numbers from console input and prints them out, one on each line, until a zero is encountered (don’t print out the zero). Identify the setup, condition, and increment. Is this a bounded or a conditional iteration? ► Sample InputSample Output

Practice Programming Problem

What’s Wrong with This Code // assume grandmasFavoriteNumber is a positive integer for(int i = 0; i != grandmasFavoriteNumber; i++) ; println("It took " + i + " iterations to guess grandma's fave number."); // What’s a better way to write this?

What’s Wrong with This Code? int years = 0; while ( years < 20 ) { double interest = balance * rate / 100; balance = balance + interest; }

What’s Wrong with This Code? int years = 20; while ( years > 0 ) { years++; double interest = balance * rate / 100; balance = balance + interest; }

What’s Wrong with This Code? float count = 0.0f; while ( count != 1.0f ) { count = count f; } // How would you fix it?

What’s Wrong with This Code? void derpNTimes(int n) { for(int i = 1; i < n; i++) println("derp"); }

What’s Wrong with This Code? void derpNTimes(int n) { for(int i = 0; i <= n; i++) println("derp"); }

Avoiding Pitfalls ► Infinite Loop ► loop body or increment statement should contain a statement that eventually leads to termination ► Real Numbers ► Avoid using == or != when using real numbers ► Use = depending on direction of loop

Avoiding Pitfalls ► 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

Nested Loops ► It is possible to have a loop within a loop ► Example (What gets printed out?) for ( int i = 0; i < 5; i++ ) { println( i ); for ( int j = 0; j < 5; j++ ) { print(" " + j ); } println(); }

Nested Loops ► The condition can vary depending on the outer loop ► Example (What gets printed out?) for ( int i = 0; i < 5; i++ ) { println( i ); for ( int j = 0; j < i; j++ ) { print( " " + j ); } println( ); }

Practice Programming Problem

How to Avoid Confusion with Nested Loops ► Focus on one loop at a time. ► Abstract away the inner loop.

Printing a Shape ► Create a triangle pattern * ** *** ► Loop through rows for ( int i = 1; i <= n; i++ ) { // make triangle row }

Printing a Shape (continued) ► 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 }

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; }

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); } By the way, the built-in print methods calls the toString method automatically

Practice Programming Problem ► Create classes to print these shapes: * * * * * * * * * * * * * * * * * * *