Introduction to Computer Programming Counting Loops.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

 Draft timetable has the same times as this semester: - ◦ Monday 9:00 am to 12:00 noon, 1:00 pm to 3:00 pm. ◦ Tuesday 9:00 am to 12:00 noon, 1:00 pm.
08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
Repeating Actions While and For Loops
Mock test review Revision of Activity Diagrams for Loops,
Fibonacci Numbers A simple example of program design.
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.
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.
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
Writing Methods. Create the method Methods, like functions, do something They contain the code that performs the job Methods have two parts.
Introduction to Methods
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.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Hello AP Computer Science!. What are some of the things that you have used computers for?
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
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:
1 Variables. 2 Receipt example What's bad about the following code? public class Receipt { public static void main(String[] args) { // Calculate total.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 5.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
Review, Pseudocode, Flow Charting, and Storyboarding.
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
February ,  2/16: Exam 1 Makeup Papers Available  2/20: Exam 2 Review Sheet Available in Lecture  2/27: Lab 2 due by 11:59:59pm  3/2:
ITP © Ron Poet Lecture 7 1 Repetition. ITP © Ron Poet Lecture 7 2 Easing Repetitive Tasks  Many computing task are repetitive.  Checking all known foods.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Counting Loops.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Java Review if Online Time For loop Quiz on Thursday.
Cumulative algorithms. 2 Adding many numbers How would you find the sum of all integers from ? // This may require a lot of typing int sum = 1 +
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Computer Science A 1. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated editor,
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Computer Programming 12 Lesson 6 – Loop structure By: Dan Lunney.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
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.
UFCFY5-30-1Multimedia Studio Coding for Interactive Media Fundamental Concepts.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Slides by Evan Gallagher
Slides by Evan Gallagher
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Repetition-Counter control Loop
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Writing Methods.
Java Fix a program that has if Online time for Monday’s Program
Introduction to Computer Programming Counting Loops 2
Control Statements Loops.
Introduction to Computer Programming
Java Fix a program that has if Online time for Monday’s Program
Week 4 Lecture-2 Chapter 6 (Methods).
Suggested self-checks:
Control Statements Loops.
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.
Presentation transcript:

Introduction to Computer Programming Counting Loops

Do something three times public class sayHello { public static void main() { System.out.println(“Let’s get started”); System.out.println(“Hello World”); System.out.println(“Hello World”); System.out.println(“Goodbye”); } You try – please code this

Why loops? Computers offer several advantages over calculators. If it is necessary, they can perform the same steps over and over again, simply by rerunning the program or calling a method many times. But is this the only way to get a computer to perform the same action repeatedly? And is this the only reason for getting a computer to repeat itself?

Loops We need the ability to perform the same set of instructions repeatedly so we don’t have to write them over and over again. This is why Java includes several ways of using repetition in a program. Each case where we repeat a set of statement is called a loop.

Counting Loops The first type of loop is a counting loop. Counting loops are repeated a specific number of times. If you read the loop, you can easily figure out how many times its statements will be performed.

Counting Loops We use a for loop to write counting loops In Java, it looks like this: for (count = start; count <= finish; count=count+1) { statements }

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

Repeat 3 times another way 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”); } You try – Print 2 lines 7 times

Print the counter 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 Number“ + count ); } System.out.println(“Goodbye”); }} You try – Try starting the counter at 10 and ending at < 14 – How many times did it print; what was in counter?

Call methods many times 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(“ *”); } You try : make the program loop to call the diamond method 3 times.

Use For loop to repeat 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 Write the code to create variables z, b and y. Write the code to calculate y and z when b is 6. Print: When b is 6, y is (and insert the value of y) and z is (and insert the value of z) Then change the value of b to 10. Print: When b is 10, y is (and insert the value of y) and z is (and insert the value of z)

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 = 5; 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+4; } 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?

Accumulating a total Variables don't remember what they were You can create a variable to increase and run it each time the loop runs. double total = 0; for (int count = 1; count <= 3; count++) { total = total + count;} // add what you are counting to what you have System.out.println(total); at end of first loop, count = 1 and total = 1 +0 = 1 at end of second loop, count = 2 and total = = 3 at end of third loop, count = 3 and total = = 6 at end of entire loop, count is gone and total = 3

Total – you try Add up the total profit as you go through the loop You will need to create a variable to hold the total and set it to 0 first. Add a statement to keep adding to the total bucket inside the loop

Outer loops Repeat a loop to print 1 – 10 3 times –Outer loops need their own counter. –You can use the fullRunCount inside the inner loop double b, z, y; for (int fullRunCount = 1; fullRunCount <= 2; fullRunCount ++) { System.out.println("Starting run # " + fullRunCount; for (int count = 1; count <= 10; count++) { System.out.println(count); System.out.println("This is part of run # " + rullRunCount;) } }

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++) { print("*"); } 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++) { print("*"); } println(); } –and now you have this shape * ** ***

Example: Interest Program 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

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.

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.1FOR Year goes from 1625 TO Present: 2.1.1Add 5% interest to the principle 2.1.2Print the current principle

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

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

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

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

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

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;

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

Output from the Compound Interest Program What will our output look like? year = 1625principle = 25.2 year = 1626principle = year = 1627principle = year = 1628principle = … … … … … year = 2001principle = E9 year = 2002principle = E9 year = 2003principle = E9 year = 2004principle = E9

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