Introduction to Computer Programming Counting Loops 2

Slides:



Advertisements
Similar presentations
08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
Advertisements

Nested for loops Cont’d. 2 Drawing complex figures Use nested for loops to produce the following output. Why draw ASCII art? –Real graphics require a.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Mock test review Revision of Activity Diagrams for Loops,
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 Computer Programming Looping Around Loops I: Counting Loops.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Loops Chapter 4. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while” structures.
CS305j Introduction to ComputingNested For Loops 1 Topic 6 Nested for Loops "Complexity has and will maintain a strong fascination for many people. It.
Building Java Programs
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Introduction to Computer Programming Counting Loops.
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
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.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loops and Iteration for Statements, while Statements and do-while Statements.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-3: Loop Figures and Constants reading: self-checks: 27 exercises:
1 BUILDING JAVA PROGRAMS CHAPTER 2 Pseudocode and Scope.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 4: Loop Figures and Constants reading:
The for loop.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Copyright 2008 by Pearson Education 1 Nested loops reading: 2.3 self-check: exercises: videos: Ch. 2 #4.
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 2: Primitive Data and Definite Loops.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
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.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Slides by Evan Gallagher
Slides by Evan Gallagher
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Introduction to Computer Science / Procedural – 67130
CSCI 161 – Introduction to Programming I William Killian
Repetition-Counter control Loop
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Fencepost loops reading: 4.1.
Number and String Operations
Building Java Programs
Control Statements Loops.
Introduction to Computer Programming
Building Java Programs
Building Java Programs
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
Building Java Programs
Suggested self-checks:
Building Java Programs
Control Statements Loops.
Drawing complex figures
Unit 3: Variables in Java
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Loops and Iteration CS 21a: Introduction to Computing I
Building Java Programs
Presentation transcript:

Introduction to Computer Programming Counting Loops 2 Review Stepwise Refinement Scope Loop Inside Loop Fence Post 1

Counting Loops We use a for loop to write loops that run a specific number of times: In Java, it looks like this: for ( count = start; count <= finish; count=count+1) { statements } 8

Counting Loops (syntax reminder) for (count = start; count <= finish; count++) statement final value of the counter initial value of the counter variable used to count times through the loop 9

Loop Example reminder public class sayHello { public static void main() System.out.println(“Let’s get started”); for ( int count = 0; // runs the first time count < 3; // test that runs each time count = count + 1) // runs all but first System.out.println(“Hello World”); } System.out.println(“Goodbye”);

Some uses Repeat statements Repeat methods Repeat formulas with new values Accumulate

Repeating method calls public class printShapes { public static void main() { System.out.println(“Get started”); diamond(); System.out.println(“All Done”); } public static void diamond() System.out.println(“ *”); System.out.println(“ * *”); System.out.println(“ * *”);

Use For loop to repeat method public class printShapes { public static void main() { System.out.println(“Get started”); for ( int count = 1; count <= 3; count = count + 1) diamond(); } System.out.println(“All Done”); public static void diamond() System.out.println(“ *”); System.out.println(“ * *”); System.out.println(“ * *”); You try: make it print 30 of these diamonds; make it print the word “ Break “ between each diamond.

Repeat formulas Remember this assignment: You are given these two formulas: z = 80/b+5 y = 2z+b What is the result when b is 10? What is the result when b is 20? What is the result when b is 30? Use a loop:

Loops: Reset variables using new values Instead of rewriting the variable setting, loop back through the setting code. b = b+4 does not change the z = statement, but the z = statement runs right after the b = statement in the loop, so the new b value is used. double b, z, y; b = 10; for (int count = 1; count <= 2; count++) { z = 80/b+5; y = 2*z+b; System.out.println(“the value of z when b is " + b + " is " + z); b = b+10; } System.out.println("the final value of z is " + z);

Repeat a formula - you try Open your quiz and copy out your profit = price – cost. See how it repeats Put your profit calculation and printing into a loop that runs 2 times, and increase the price by 5 inside the loop. It will look something like: Cost = 2; Price = 5.5; for (int count = 1; count <=2; count++) { totalValue=price-cost; System.out.println(totalValue); price=price+5; } See how it reruns the formula with the new values. Add 1 to the cost also and rerun it to see what happens. Add a line to print the count so you can see its value as it loops. Does it work if you put price == 5.5 inside the loop? – try it Does it work if you change the order of these lines – try it

Loops: Scope of Variables Variables created in loops disappear when the loop ends You can create the counter before the loop if you want to keep it for the entire program. double b, y; b = 5; int count; for (count = 1; count <= 2; count++) { double z = 80/b+5; y = 2*z+b; System.out.println(“the value of z when b is " + b + " is " + z); b = b+4; } System.out.println("the final value of z is " + z); // can't do this because z was created inside loop.

Scope – you try More changes to our profit calculator: Add code after the loop ends (after the }) to print totalValue and price. Do you see the first price or last price? Try to print count then also after the loop and see that it wont compile – Why not? Create count (int count;) before the loop starts instead, and then try to print count after the loop – why does that work now? What happens when you create totalValue inside the loop instead of before the loop?

Design– Stepwise refinement Approach problem by writing algorithm at high level and refining details down to code level Flow chart

Example: Interest Program - problem Example - Write a program that calculates the interest that the Canarsie Indians would have accumulated if they had put the $24 that they had received for Manhattan Island in the bank at 5% interest. Input - none; all the values are fixed Output - Year and Principle Other Information - Principle is initially 24 Interest = Interest Rate * Principle New Principle = Old Principle + Interest 27

Example: Interest Program Our initial algorithm is: 1. Set the principle to 24 2. For every year since 1625, add 5% interest to the principle and print out the principle. 28

Refining The Interest Algorithm 1. Set the principle to 24 2. For every year since 1625, add 5% interest to the principle and print out the principle. 2.1 FOR Year goes from 1625 TO Present: 2.1.1 Add 5% interest to the principle 2.1.2 Print the current principle 29

Refining The Interest Algorithm 1. Set the principle to 24 2.1 FOR Year goes from 1625 TO Present: 2.1.1 Add 5% interest to the principle 2.1.2 Print the current principle 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 30

Refining The Interest Algorithm 1. Set the principle to 24 2.1 FOR Year goes from 1625 TO Present: 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle principle = 24; 31

Refining The Interest Algorithm principle = 24; 2.1 FOR Year goes from 1625 TO Present: 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle for (year = 1625; year < present; year++) { } 32

Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle } interest = rate * principle; principle = principle + interest; 33

Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; 2.1.2 Print the current principle } System.out.println("year = " + year + "\tprinciple = “ + principle); 34

The Interest Program public class Interest { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(String[] args) { final int present = 2005; int year; final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24; 35

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; System.out.println("year = " + year + "\tprinciple = " + principle); } 35

Output from the Compound Interest Program What will our output look like? year = 1625 principle = 25.2 year = 1626 principle = 26.46 year = 1627 principle = 27.783 year = 1628 principle = 29.172150000000002 … … … … … year = 2001 principle = 2.3365602874289446E9 year = 2002 principle = 2.4533883018003917E9 year = 2003 principle = 2.5760577168904114E9 year = 2004 principle = 2.704860602734932E9 37

Outer loops Repeat a loop to print 1 – 10 3 times Outer loops need their own counter. The inner loop can use both its own counter and the outer loop’s counter for (int fullRunCount = 1; fullRunCount <= 3; fullRunCount ++) { System.out.println("Starting run # " + fullRunCount); for (int count = 1; count <= 10; count++) { System.out.println(count + “part of run “ + fullRunCount); }

You Try Print 1 to 30 by 5’s, and then repeat that 3 times: 5 10 15 20 25 30 5 10 15 20 25 30 5 10 15 20 25 30 Extra1: Each time you repeat, drop the first number 5 10 15 20 25 30 10 15 20 25 30 15 20 25 30

You Try Answer for (int fullRunCount = 1; fullRunCount <= 3; fullRunCount ++) { for (int count = 5 ; count <= 30; count= count + 5) System.out.print(count + " "); } To make the Extra1 work, for (int count = 5 * fullRunCount)

Outer loop shapes First I have a loop that prints 7 stars in a row using a loop. When the loop is done, go to the next line. Now add an outer loop to print the 7 stars 3 times. (remember to use a different counter) for (int fullRunCount = 1; fullRunCount <=3; fullRunCount++) { for (int count = 1; count <=7; count++) System.out.print("*"); } System.out.println(); and now you have *******

Outer loop shapes You can use the outer control counter as a variable inside the inner loop. Now print as many stars as the counter in the outer loop for (int fullRunCount = 1; fullRunCount <=3; fullRunCount++) { for (int count = 1; count <=fullRunCount; count++) System.out.print("*"); } System.out.println(); and now you have this shape * ** ***

Outer loop shapes You can have many inner loops inside an outer loop Now print as many stars as the counter in the outer loop for (int fullRunCount = 1; fullRunCount <=3; fullRunCount++) { for (int count = 1; count <=3-fullRunCount; count++) System.out.print(" "); } for (int count = 1; count <=fullRunCount; count++) System.out.print("*"); System.out.println(); and now you have this shape * 2 spaces 1 star ** 1 space 2 stars *** 0 spaces 3 stars

Remove the magic number 3 int basewidth = 3; for (int fullRunCount = 1; fullRunCount <=basewidth; fullRunCount++) { for (int count = 1; count <=basewidth-fullRunCount; count++) System.out.print(" "); } for (int count = 1; count <=fullRunCount; count++) System.out.print("*"); System.out.println();

You try: make a diamond Make a method to print the top half of a diamond that is 5 wide at its base and 1 wide at the top. * 2 spaces, 1 star *** 1 space, 3 stars ***** 0 space, 5 stars Hint: if outer loop is 1,2,3 Make a method to print the bottom half. Extra: print the entire diamond 10 times Extra: make the size of the diamond base a variable

You try: make a diamond Make a method to print the top half of a diamond that is 5 wide at its base and 1 wide at the top. * 2 spaces, 1 star *** 1 space, 3 stars ***** 0 space, 5 stars Hint: if outer loop is 1,2,3 Fill out this chart: Outer Spaces needed Spaces alg Stars needed Stars alg

You try: make a diamond- chart Make a method to print the top half of a diamond that is 5 wide at its base and 1 wide at the top. * 2 spaces, 1 star *** 1 space, 3 stars ***** 0 space, 5 stars Hint: if outer loop is 1,2,3 Fill out this chart: Outer Spaces needed Spaces alg Stars needed Stars alg 2 1 5- 2*Outer 3 outer 5

You try Diamond Top Answer int basewidth = 5; for (int fullRunCount = basewidth/2+1; fullRunCount >=0; fullRunCount--) { for (int count = 1; count <= fullRunCount; count++) System.out.print(" "); } for (int count = 1; count <= basewidth -2*fullRunCount; count++) System.out.print("*"); System.out.println();

You try Diamond Bottom int basewidth = 5; for (int fullRunCount = 1; fullRunCount < basewidth/2+1; fullRunCount++) { for (int count = 1; count <= fullRunCount; count++) System.out.print(" "); } for (int count = 1; count <= basewidth -2*fullRunCount; count++) System.out.print("*"); System.out.println();

Important Loop Facts loops repeat the code in braces Still goes line by line – (you should now know which line the system will read next) variables persist with their value until they are destroyed – they don't reset at the beginning of a loop (unless a statement you write specifically sets it to 0). variables created inside a loop are destroyed at the end of a loop Loops can be inside other loops You can accumulate a total by adding a new value to the accumulated total held in another variable. (total = total + whatever); - remember to start total at 0.

Summary Stepwise Refinement – Approach as algorithm stepping down in detail until you get to code Scope – variables die when the block they are created inside ends. Can create before block and use inside block Loop Inside Loop – Inside loop can use outside loops counter cleverly for control