introduction to computer programming counting loops

33
Introduction to Computer Programming Counting Loops

Upload: tabitha-potter

Post on 30-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to Computer Programming Counting Loops

Introduction to Computer Programming

Counting Loops

Page 2: 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(“Hello World”);

System.out.println(“Goodbye”);

}

}

You try – please code this

Page 3: Introduction to Computer Programming Counting Loops

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?

Page 4: Introduction to Computer Programming Counting Loops

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.

Page 5: Introduction to Computer Programming Counting Loops

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.

Page 6: Introduction to Computer Programming Counting Loops

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

}

Page 7: Introduction to Computer Programming Counting Loops

Counting Loops (continued)

for (count = start; count <= finish; count++)

statement

variable used to counttimes through the loop

initial value of the counter

final value ofthe counter

Page 8: Introduction to Computer Programming Counting Loops

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

Page 9: Introduction to Computer Programming Counting Loops

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?

Page 10: Introduction to Computer Programming Counting Loops

Call methods many times public class printShapes {

public static void main()

{

System.out.println(“Get started”);

diamond();

diamond();

diamond();

System.out.println(“All Done”);

}

public static void diamond()

{

System.out.println(“ *”);

System.out.println(“ * *”);

System.out.println(“ * *”);

System.out.println(“ * *”);

System.out.println(“ *”);

}

}

You try : make the program loop to call the diamond method 3 times.

Page 11: Introduction to Computer Programming Counting Loops

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(“ * *”);

System.out.println(“ * *”);

System.out.println(“ *”);

}

}

You try: make it print 30 of these diamonds; make it print the word “ Break “ between each diamond.

Page 12: Introduction to Computer Programming Counting Loops

Repeat formulas• Remember this assignment: You are given these two formulas:

z = 80/b+5y = 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)

Page 13: Introduction to Computer Programming Counting Loops

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

Page 14: Introduction to Computer Programming Counting Loops

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

Page 15: Introduction to Computer Programming Counting Loops

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.

Page 16: Introduction to Computer Programming Counting Loops

Scope – you tryMore 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?

Page 17: Introduction to Computer Programming Counting Loops

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 haveSystem.out.println(total);

at end of first loop, count = 1 and total = 1 +0 = 1at end of second loop, count = 2 and total = 2 + 1 = 3at end of third loop, count = 3 and total = 3 + 3 = 6at end of entire loop, count is gone and total = 3

Page 18: Introduction to Computer Programming Counting Loops

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

Page 19: Introduction to Computer Programming Counting Loops

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

}

}

Page 20: Introduction to Computer Programming Counting Loops

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*********************

Page 21: Introduction to Computer Programming Counting Loops

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******

Page 22: Introduction to Computer Programming Counting Loops

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 fixedOutput - Year and PrincipleOther Information -

Principle is initially 24Interest = Interest Rate * PrincipleNew Principle = Old Principle + Interest

Page 23: Introduction to Computer Programming Counting Loops

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.

Page 24: Introduction to Computer Programming Counting Loops

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 principle2.1.2 Print the current principle

Page 25: Introduction to Computer Programming Counting Loops

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 principle2.1.2 Print the current principle

2.1.1.1 Calculate 5% Interest2.1.1.2 Add the interest to the principle

Page 26: Introduction to Computer Programming Counting Loops

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% Interest2.1.1.2 Add the interest to the principle2.1.2 Print the current principle

principle = 24;

Page 27: Introduction to Computer Programming Counting Loops

Refining The Interest Algorithm

principle = 24;

2.1 FOR Year goes from 1625 TO Present:2.1.1.1 Calculate 5% Interest2.1.1.2 Add the interest to the principle2.1.2 Print the current principle

for (year = 1625; year < present; year++) {

}

Page 28: Introduction to Computer Programming Counting Loops

Refining The Interest Algorithmprinciple = 24;for (year = 1625; year < present; year++)

{

2.1.1.1 Calculate 5% Interest2.1.1.2 Add the interest to the principle2.1.2 Print the current principle}

interest = rate * principle;principle = principle + interest;

Page 29: Introduction to Computer Programming Counting Loops

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

Page 30: Introduction to Computer Programming Counting Loops

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;

Page 31: Introduction to Computer Programming Counting Loops

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

Page 32: Introduction to Computer Programming Counting Loops

Output from the Compound Interest Program

•What will our output look like?year = 1625 principle = 25.2year = 1626 principle = 26.46year = 1627 principle = 27.783year = 1628 principle = 29.172150000000002

… … … … … year = 2001 principle = 2.3365602874289446E9year = 2002 principle = 2.4533883018003917E9year = 2003 principle = 2.5760577168904114E9year = 2004 principle = 2.704860602734932E9

Page 33: Introduction to Computer Programming Counting Loops

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.