Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th...

Post on 08-Jan-2018

219 views 0 download

description

Style /* * Author: me! * Date: 9/26/04 * Time: d+(int)d/x minutes * Comment: The virtual lyricist */ class CS5App { public static void main(String[] args) { H.pl(“Enter your favorite mascot: ”); String mascot = H.nw(); … more code here … } leave space before blocks of code leave space between parts of code that do different things introductory comment indent code evenly within the surrounding braces align curly braces that correspond use reasonable variable names

Transcript of Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th...

• Code Compression the benefits of looping...

Today in CS 5

• HW 4 - (3 problems)M/T sections

W/Th sections

due Sunday, 9/26 at midnightdue Monday, 9/27 at midnight

Reading: Class notes for week 4Coding style & commenting will count for HW4 !

• Let’s Make a Deal

• Friday, 8:00 am – recitation section

• Grading and the submission website... concerns?questions?

optional, but all are

welcome!

Lab: N-Z all others welcome!

Today in CS 5

• Code Compression the benefits of looping...

int i = 0;while (i < 4){ ++i;}

for (int i=0 ; i<4 ; ++i){ ;}

for loop while loopmore braces!

Style

/* * Author: me! * Date: 9/26/04 * Time: d+(int)d/x minutes * Comment: The virtual lyricist */

class CS5App { public static void main(String[] args) { H.pl(“Enter your favorite mascot: ”);

String mascot = H.nw(); … more code here … }}

leave space before blocks of code

leave space between parts of code that do different things

introductory comment

indent code evenly within the surrounding braces

align curly braces that correspond

use reasonable variable names

Comments ?

/* * Author: me! * Date: 9/26/04 * Time: 3 kiloseconds * Comment: Finding the max and min of 4 values */

if ( a < b && a < c && a < d ) // see if a is minimal{ H.pl(“ Minimum is ” + a);}

else if ( b < a && b < c && b < d ) // see if b is minimal{ H.pl(“ Minimum is ” + b);}

introductory comment

comment at least each block of code

very small blocks need only one comment for the entire group

Back inside the machine...

Shortcuts for changing variables:

i++;++i;

int i = 35;

i = i + 1; i += 1;

Back inside the machine...

Shortcuts for changing variables:

i++;++i;

int i = 35;

i = i + 1; i += 1;

all of these increment i by 1

Back inside the machine...

Shortcuts for changing variables:

i++;++i;

int i = 35;

i = i + 1; i += 1;

int amoebas = 100000;amoebas = amoebas * 2;

double hwToGo = 11.0;hwToGo = hwToGo - 1;

long u235 = 10000000000000L;u235 = u235 / 2;

all of these increment i by 1

Back inside the machine...

Shortcuts for changing variables:

i++;++i;

int i = 35;

i = i + 1; i += 1;

int amoebas = 100000;amoebas = amoebas * 2;

double hwToGo = 11.0;hwToGo = hwToGo - 1;

long u235 = 10000000000000L;u235 = u235 / 2;

all of these increment i by 1

amoebas *= 2;

hwToGo -= 1; --hwToGo;

u235 /= 2;

An aside

What’s the difference between i++++i and ?

Nothing -- when they are on their own!

An aside

What’s the difference between i++++i and ?

Nothing -- when they are on their own!

When they are being used and set at the same time things change...

int i = 32;

int x = ++i + 10;

int i = 32;

int x = i++ + 10;

increments after useincrements before use

An aside

What’s the difference between i++++i and ?

Nothing -- when they are on their own!

When they are being used and set at the same time things change...

int i = 32;

int x = ++i + 10;

int i = 32;

int x = i++ + 10;

increments after useincrements before use

i is 33

x is 43

i is 33

x is 42

Hw 4, Problem 1

Hw4Pr1) The improved math menu ...

Option # 2: this integral

Option # 4: unlimited max and min

Hw4Pr2) Let’s Make a Deal !

Hw4Pr3) Let’s Make A LOT of Deals.

Option # 3: function graphing

Option # 0: sequences

Option # 1: raw power

dx

x = 0

x =

the period of a pendulum with length L and initial angle a

Pair Programming Problem

code != work

Sequencing items with a single piece of code

7 14 21 28 35

3 6 9 18 21

2 22 222

42 42 42 42 42

code != work

Sequencing items with a single piece of code

7 14 21 28 35 42

3 6 9 18 21 42

2 22 222 2222

42 42 42 42 42 42

Anatomy of a for loop

for ( int i = 0 ; i < 4 ; ++i ){ H.pl(i);}

Anatomy of a for loop

for ( int i = 0 ; i < 4 ; ++i ){ H.pl(i);}

PART 1 PART 2

PART 3PART 4

Anatomy of a for loop

for ( int i = 0 ; i < 4 ; ++i ){ H.pl(i);}

PART 1 PART 2

PART 1

PART 4int i

0

PART 2PART 3PART 4

create and initialize loop variable

PART 3

test to determine if we run the loop

loop body is run if test is true

update the loop variable

alwaystrue false

i<4

end loop

code != work

Sequencing items with a single piece of code

7 14 21 28 35 42

3 6 9 18 21 42

2 22 222 2222

42 42 42 42 42 42

an egocentric for loop

for ( int i = 1 ; i <= 6 ; ++i ){ H.p( 7*i );}

a selfless for loop

int x = 42; for ( int i = 0 ; i < 6 ; ++i ){

H.p( x + “ ” );

}

sharing with if

int x = 3; for ( int i = 0 ; i < 6 ; ++i ){ H.p( x + “ ” ); if (x%2 == 0) else

}

“Quiz” Print the output of these loops

A

B

C

int s = 0;for (int i = 1 ; i < 5 ; ++i){ H.p( i + “ ” ); s = s + i;}H.pl(“\ns is ” + s);

int c = 0;for (int i=10 ; i>0 ; i/=2 ){ H.p( i + “ ” ); c++;}H.pl(“c is ” + c);

for (int i = 0 ; i != 4 ; i+=1){ H.p( i + “ ” );}

“Extra Credit” change one character in the code above so that this loop runs 4294967292 times.

“Quiz”, part 2

0 1 2 3 6 7 14 15 30

Write a loop to print this sequence:9 terms total

2 22 222 2222 ... 9 terms total

Write a loop to print this sequence:

Hint: Use a for loop with an if inside it!

Hint: Use a for loop with a for loop inside it!

Variables: a life story...

int sum = 0;for ( int i = 1 ; i < 5 ; ++i ){ sum = sum + i;}

H.pl(“sum is ” + sum);

int sum = 0;for ( int i = 0 …

Why will java complain about this ?!?

Variables: a life story...

int sum = 0;for ( int i = 1 ; i < 5 ; ++i ){ sum = sum + i;}

H.pl(“sum is ” + sum);

int sum = 0;for ( int i = 0 …

(1) Birth (of sum and i)

Why will java complain about this ?!?

Variables: a life story...

int sum = 0;for ( int i = 1 ; i < 5 ; ++i ){ sum = sum + i;}

H.pl(“sum is ” + sum);

int sum = 0;for ( int i = 0 …

(1) Birth (of sum and i)

(2) Growth

Why will java complain about this ?!?

Variables: a life story...

int sum = 0;for ( int i = 1 ; i < 5 ; ++i ){ sum = sum + i;}

H.pl(“sum is ” + sum);

int sum = 0;for ( int i = 0 …

(1) Birth (of sum and i)

(2) Growth

(3) Death (of i)but sum lives on…

Why will java complain about this ?!?

Variables: a life story...

int sum = 0;for ( int i = 1 ; i < 5 ; ++i ){ sum = sum + i;}

H.pl(“sum is ” + sum);

sum = 0;for ( int i = 0 …

(1) Birth (of sum and i)

(2) Growth

(3) Death (of i)but sum lives on…

reuse is OKrecreation is not!

What’s this all for ?

Program for finding the factorial of a number…

H.pl(“Type an integer n and I will print n!”);int n = H.ni(); // we have n – we need n factorial

int result = ; // be sure to give an initial value

H.pl(“The result is ” + result);Use the same idea for creating powers in Hw4 Pr1 !

Perspective on for loops

// Name: CS5App// Author: Matt Beaumont// Purpose: To get me out of CS5...// ...no, really...// Purpose: To create and maintain a list // of films and directors

/* Notes: * I haven't liked for-loops since the day I met them. * They bother me for some reason. Hence, no for-loops… */

class CS5App{ ...

At the top of a CS 5 placement project file …

Extreme Looping

Java’s last and least built-in variable type: boolean

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”);}

“while” block

Extreme Looping

Java’s last and least built-in variable type: boolean

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”);}

“while” block

note what’s NOT here!

Extreme Looping with while

No variable or expression is needed!

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”); int escape = H.randInt(1,100); if (escape == 100) { break; }}

worry later about how to

escape !

here is how to quit – use break

!

“User – friendly” codelong myNumber = H.randLong(0,9000000000000000000L);

while ( true ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni();

if ( yourGuess == myNumber ) { break; // let me out ! }}

A break breaks out of the enclosing switch, for, or

while.

“User – friendly” codelong myNumber = H.randLong(0,9000000000000000000L);

while ( true ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni();

if ( yourGuess == myNumber ) break; // let me out !

H.p(“Would you like to continue playing? ”); String answer = H.nl(); if (answer == “no”) break;}

but friendlier!

same as

before

Monty Hall

Let’s make a deal ’63-’86

Sept. 1990

inspiring the “Monty Hall paradox”

Hw4Pr2) The Virtual Monty Hall

The two Monte Carlos

Monte Carlo casino, Monaco

Making random numbers work

for you!

Monte Carlo methods, Math/CS

• math hw• cs hw

• physics hw• Hum hw

Monte Carlo Monty Hall

Suppose you always switch to the other door...What are the chances that you will win the car ?

Hw4Pr3) Monte Carlo Monty Hall

Run it (randomly) 1000 times and see!

Monty Hall program design

top-down software engineering

while (true) // program skeleton via short comments{

}

HW4PR3) Virtual Monty Hall

Detailed design this Friday in

recitation…

Monte Carlo in action

Suppose you roll two dice.What are the chances that you roll doubles?

int doublesCount = 0;

for (int i=0 ; i<1000 ; ++i){ int d1 = H.randInt(1,6); int d2 = H.randInt(1,6);

if ( d1 == d2 ) { ++doublesCount; }}

H.pl(“We rolled ” + doublesCount + “ doubles.”);

one roll of the dice

1000 times

count the number of doubles rolled

set up a variable to count the number of doubles rolled

Summary

for loop examples

while loop examples

statements and shortcuts for changing variables

for (int i=12 ; i>=0 ; i-=2){ H.p( i + “ ” );}

int x = 3;for (int i=0 ; i<9 ; ++i){ H.p( x + “ ” ); x = x + 12;}

x *= 10; num += 10;

while ( true ){ String s = H.nw(); if (s.equals(“no”)) break;}

++i; i++; --i; i--;multiply x by 10 increase num by 10 increase i by 1 decrease i by 1

prints 12 10 8 6 4 2 0prints 3 15 27 39 51 63 75 87 99

continues until the user types “no”

Lab Today

• I’d suggest starting by writing the for loops in Hw4Pr1

• then move on to the more involved examples...

10 15 20 25 30 35 40 45 50 55 60 6511 22 33 44 55 66 77 88 99 110 1211 2 4 8 16 32 64 128 256 512 1024 20480 3 9 12 36 39 117 120 360 363 10891 22 333 4444 55555 666666 7777777 88888888

use loops to print these sequences

Hw4Pr2

Hw4Pr3 Monte Carlo Monty Hall (for)

Virtual Monty Hall (while)

print the sum of the first four sequences, too …

N-Z all others welcome!

Hw4Pr1) Improved Math Menu Pair Programming Problem

Summary

for loop examples

while loop examples

statements and shortcuts for changing variables

for (int i=12 ; i>=0 ; i-=2){ H.p( i + “ ” );}

int x = 3;for (int i=0 ; i<9 ; ++i){ H.p( x + “ ” ); x = x + 12;}

x *= 10; num += 10;

while ( true ){ String s = H.nw(); if (s.equals(“no”)) break;}

++i; i++; --i; i--;multiply x by 10 increase num by 10 increase i by 1 decrease i by 1

prints 12 10 8 6 4 2 0prints 3 15 27 39 51 63 75 87 99

continues until the user types “no”

“Quiz” Print the output of these loops:

Names:

A

B

C

int s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i+=1 ){ H.p( i + “ ” );}

“Quiz”, part 2

0 1 2 3 6 7 14 15 30

Write a loop to print this sequence:9 terms total

0 00 000 0000 ... 9 terms total

Write a loop to print this sequence:

Hint: Use a for loop with an if inside it!

Hint: Use a for loop with a for loop inside it!

A

Cint s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i = i-2){ H.p( i + “ ” );}

prints

prints

prints

B

int s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i = i-2){ H.p( i + “ ” );} 10 8 6 4 2

prints

prints

prints

A

C

B

int s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i = i-2){ H.p( i + “ ” );} 10 8 6 4 2

10 5 2 1 0prints

prints

prints

int s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i = i-2){ H.p( i + “ ” );} 10 8 6 4 2

10 5 2 1 0prints

prints

prints1 2 3 4s is 10

A

C

B

0 1 2 3 6 7 14 15 30Write a loop to print this sequence:9 terms total

int x = 0;for (int i=0 ; i<9 ; ++i){ H.p( x + “ ” );

if ( i%2 == 0 ) { x = x + 1; } else { x = x * 2; }}

i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8

shorter?

0 1 2 3 6 7 14 15 30Write a loop to print this sequence:9 terms total

int x = 0;for (int i=0 ; i<9 ; ++i){ H.p( x + “ ” );

if ( i%2 == 0 ) ++x; else x *= 2;}

i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8

ifs and elses have one-line bodies (“blocks”) if no curly

braces are used

0 00 000 0000 ... Write a loop to print this sequence:

9 terms total

for (int i=1 ; i<10 ; ++i){ for (int j=1 ; j<=i ; ++j) { H.p(0); } H.p(“ ”);}

i = 1 i = 2 i = 3 i = 4

j = 1 j = 3j = 1j = 2

j = 1j = 2

j = 3j = 1j = 2 j = 4

shorter?

0 00 000 0000 ... Write a loop to print this sequence:

9 terms total

for (int i=1 ; i<10 ; ++i){ for (int j=1 ; j<=i ; ++j) H.p(0);

H.p(“ ”);}

i = 1 i = 2 i = 3 i = 4

j = 1 j = 3j = 1j = 2

j = 1j = 2

j = 3j = 1j = 2 j = 4

ifs and elses have one-line bodies (“blocks”) if no curly

braces are used

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

(1) Birth (of sum and x)

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

(1) Birth (of sum and x)

(2) Growth

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

A variable’s scope is the block of code in which it is declared.

(1) Birth (of sum and x)

A variable only exists until the closing curly brace of its scope...

(2) Growth

(3) Death (of x)

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

int sum = 0;for … next loop here …

(1) Birth (of sum and x)

(2) Growth

(3) Death (of x)

Why will java complain about this ?!?

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

sum = 0;for … next loop here …

(1) Birth (of sum and x)

(2) Growth

(3) Death (of x)

You can reuseBut you can’t redeclare !

What’s this all for ?

Program for factorial input: an integer noutput: the integer n!

case 1:{ H.pl(“Type an integer n and I will print n!”); int n = H.ni(); // we have n – we need n!

} Use the same idea for creating powers !

Extreme Looping with while

No variable or expression is needed!

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”);}

worry later about how to

escape !

Extreme Looping with while

No variable or expression is needed!

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”); int escape = H.randInt(1,100); if (escape == 100) { break; }}

worry later about how to

escape !

here is how to quit – use break

!

“User – friendly” codelong myNumber = H.randLong(0,9000000000000000000L);

while ( true ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni();

if ( yourGuess == myNumber ) { break; // let me out ! }}

A break breaks out of the enclosing switch, for, or

while.

“User – friendly” codelong myNumber = H.randLong(0,9000000000000000000L);

while ( true ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni();

if ( yourGuess == myNumber ) { break; // let me out ! }

H.p(“Would you like to continue playing? ”); String answer = H.nl(); if (answer == “no”) break;}

much friendlier!

same as

before

Monty Hall

Let’s make a deal ’63-’86

Sept. 1990

inspiring the “Monty Hall paradox”

Monte Carlo Monty Hall

Suppose you always switch to the other door...What are the chances that you will win the car ?

Hw4Pr3) Monte Carlo Monty Hall

Run it (randomly) 1000 times and see!

The two Monte Carlos

Monte Carlo casino, Monaco

Making random numbers work

for you!

Monte Carlo methods, Math/CS

• math hw• cs hw

• physics hw• Hum hw

Summary

for loop examples

while loop examples

statements and shortcuts for changing variables

for (int i=12 ; i>=0 ; i-=2){ H.p( i + “ ” );}

int x = 3;for (int i=0 ; i<9 ; ++i){ H.p( x + “ ” ); x = x + 12;}

x *= 10; num += 10;

while ( true ){ String s = H.nw(); if (s.equals(“no”)) break;}

++i; i++; --i; i--;multiply x by 10 increase num by 10 increase i by 1 decrease i by 1

prints 12 10 8 6 4 2 0prints 3 15 27 39 51 63 75 87 99

continues until the user types “no”

Hw4, Pr1, Option 2: integration!

Hw4, Pr1, Option 2: integration!Prof. Jacobsen goes hungry...

Monte Carlo in action

Suppose you roll two dice.What are the chances that you roll doubles?

int doublesCount = 0;

for (int i=0 ; i<1000 ; ++i){ int d1 = H.randInt(1,6); int d2 = H.randInt(1,6);

if ( d1 == d2 ) { ++doublesCount; }}

H.pl(“We rolled ” + doublesCount + “ doubles.”);

one roll of the dice

1000 times

count the number of doubles rolled

set up a variable to count the number of doubles rolled

Lab Today

• I’d suggest starting by writing the for loops in Hw4Pr1

• then move on to the more involved examples...

10 15 20 25 30 35 40 45 50 55 60 6511 22 33 44 55 66 77 88 99 110 1211 2 4 8 16 32 64 128 256 512 1024 20480 3 9 12 36 39 117 120 360 363 10891 22 333 4444 55555 666666 7777777 88888888

use loops to print these sequences

Hw4Pr2

Hw4Pr3 Monte Carlo Monty Hall (for)

Virtual Monty Hall (while)

print the sum of just the first four sequences, too …

N-Z and any others…

Hw4, Pr1, Option 4: random sumsSee the Improved Moth Menu for working example code at www.cs.hmc.edu/~dodds/cs5

case 4:{ Histogram h = new Histogram(); for (int i=0 ; i<50000 ; ++i) h.addPoint(Math.random()); outerFrame.updateSize(); break; }

Your task: plot sums of random numbers

min x is ~0 max x is ~1

current plot: 50000 random numberscurrent code: 50000 random numbers

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.out.print( x + “ ” ); x = x*3;}

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(2) Growth

(3) Death

A variable only exists until the closing curly brace of its scope...

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(3) Death

A variable only exists until the closing curly brace of its scope...

A variable’s scope is the block of code in which it is declared.

(2) Growth

(3) Death

A variable only exists until the closing curly brace of its scope...

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.out.print( x + “ ” ); x = x*3;}

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(2) Growth

(3) Death

A variable only exists until the closing curly brace of its scope...

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.out.print( x + “ ” ); x = x*3;}

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(2) Growth

(3) Death

A variable only exists until the closing curly brace of its scope...

Back inside the machine...

Shortcuts for changing variables:

i++;++i;

int i = 33;

i = i + 1; i += 1;

int amoebas = 100000;amoebas = amoebas * 2;

double hwToGo = 11.0;hwToGo = hwToGo - 1;

long u235 = 10000000000000L;u235 = u235 / 2;

Program design

top-down software engineering in general:

start with program skeleton

boolean done = false;while ( !done ){ add details to structure compile && run program if ( everything == OK ) done = true;}

Anatomy of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

the “for” block

#0 - create and initialize loop variables

#1 - check the test condition

#2 - execute all of the code in the “for” block

#3 - update loop variables as desired; goto #1

if false, stop looping & jump past the “for” blockif true, continue looping

initialization statement testvariable updates

0 1

2

3

Anatomy of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

#0 - create and initialize loop variables

initialization statement

int i

0

Anatomy of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

#0 - create and initialize loop variables

#1 - check the test conditionif false, stop looping & jump past the “for” blockif true, continue looping

test

int i

0

Anatomy of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

#0 - create and initialize loop variables

#1 - check the test condition

#2 - execute all of the code in the “for” block

if false, stop looping & jump past the “for” blockif true, continue looping

the “for” block

i is 0

int i

0

output

Anatomy of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

#0 - create and initialize loop variables

#1 - check the test condition

#2 - execute all of the code in the “for” block

#3 - update loop variables as desired; goto #1

if false, stop looping & jump past the “for” blockif true, continue looping

variable updates

i is 0output

int i

1

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

output:

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

i is 0output:

startcontinue looping if true

int i

0int i

1

before after

continue looping if true

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

i is 0i is 1

output:

start

int i

1int i

2

before after

continue looping if true

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

i is 0i is 1i is 2

output:

start

int i

2int i

3

before after

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

i is 0i is 1i is 2

…i is 8

output:

start

int i

8int i

9

before after

continue looping if true

Execution of a for loop

for ( int i = 0 ; i < 9 ; ++i ){ H.out.println(“i is ” + i);}

i is 0i is 1i is 2

…i is 8

output:

start

int i

8int i

9

before after

jump to end of for loop if false

continue looping if true

Monty Hall

Let’s make a deal ’63-’86

Sept. 1990

inspiring the “Monty Hall paradox”

Monte Carlo

Monte Carlo casino, Monaco

Estimating a value (usually a probability) by playing an appropriate game over and over.

Monte Carlo methods, Math/CS

“Quiz” Print the output of these loops:

Names:

A

B

C

int s = 0;for (int x = 1 ; x < 5 ; ++x){ H.p( x + “ ” ); s = s + x;}H.pl(“\ns is ” + s);

int i = 20;while (i > 0){ i /= 2; H.p( i + “ ” );}

for (int i = 10 ; i > 0 ; i = i-2){ H.p( i + “ ” );}

“Quiz”, part 2

0 1 2 3 6 7 14 15 30

Write a loop to print this sequence:9 terms total

0 00 000 0000 ... 9 terms total

Write a loop to print this sequence:

Hint: Use a for loop with an if inside it!

Hint: Use a for loop with a for loop inside it!

“Quiz”, part 2

0 1 2 3 6 7 14 15 30What code (using for) will print9 terms total

Hw4Pr1) Option #1: sequences

0 1 2 3 6 7 14 15 30

Mixing it up... Hw4Pr1) Option #1: sequences

0 00 000 0000…What code (using for) will print9 terms total

User - friendly codeboolean playAgain = true;long mynumber = (long)(Math.random()*9000000000000000000L);

while ( playAgain ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourguess = H.ni();

if ( yourguess == mynumber ) { playAgain = false; // let me out ! }}

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.p( x + “ ” ); x = x*3;}

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.p( x + “ ” ); x = x*3;}

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(2) Growth

A variable only exists until the closing curly brace of its scope...

Variables: a life story...

for ( int i = 0 ; i < 6 ; ++i ){ int x = 1; H.p( x + “ ” ); x = x*3;}

A variable’s scope is the block of code in which it is declared.

(1) Birth (of x and i)

(2) Growth

(3) Death

A variable only exists until the closing curly brace of its scope...

Monty Hall program design

top-down software engineering HW4PR3) Virtual Monty Hall

write program skeleton

while ( true ){ add more details compile && run program if ( everything == OK ) break;}

H.pl(“Time to work on Chem...”);

0 00 000 0000 ... Write a loop to print this sequence:

9 terms total

for (int i=1 ; i<10 ; ++i){ for (int j=1 ; j<=i ; ++j) { H.p(0); } H.p(“ ”);}

i = 1 i = 2 i = 3 i = 4

j = 1 j = 3j = 1j = 2

j = 1j = 2

j = 3j = 1j = 2 j = 4

shorter?

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

A variable’s scope is the block of code in which it is declared.

(1) Birth (of sum and x)

A variable only exists until the closing curly brace of its scope...

(2) Growth

(3) Death (of x)

Variables: a life story...

int sum = 0;for ( int x = 0 ; x < 6 ; ++x ){ H.p( x + “ ” ); sum = sum + x;} H.pl(“sum is ” + sum);

sum = 0;for … next loop here …

(1) Birth (of sum and x)

(2) Growth

(3) Death (of x)

You can reuseBut you can’t redeclare !

What’s this all for ?

Program for factorial input: an integer noutput: the integer n!

case 1:{ H.pl(“Type an integer n and I will print n!”); int n = H.ni(); // we have n – we need n!

} Use the same idea for creating powers !

Extreme Looping with while

No variable or expression is needed!

H.pl(“It keeps on”);

while ( true ){ H.pl(“going and”); double r = Math.random(); if (r > 0.99) { break; }}

worry later about how to

escape !

here is how to quit – use break

!

“User – friendly” codelong myNumber = (long)(Math.random()*9000000000000000000L);

while ( true ){ H.pl(“I’m thinking of a positive integer”); H.pl(“If you guess it, you may leave.”); H.pl(“Otherwise, you must continue…\n”); H.p(“What is your guess? ”); int yourGuess = H.ni();

if ( yourGuess == myNumber ) { break; // let me out ! }}

A break breaks out of the enclosing switch, for, or

while.