Transcript Lec4.ppt
Today in CS 5
• Code Compression
Lab: N-Z
all others
welcome!
the benefits of looping...
• Grading and the submission website...
concerns?
questions?
• Let’s Make a Deal
• HW 4 - (3 problems)
due Sunday, 9/26 at midnight
due Monday, 9/27 at midnight
Coding style & commenting will count for HW4 !
Reading: Class notes for week 4
• Friday, 8:00 am – recitation section
optional, but all
are welcome!
M/T sections
W/Th sections
Today in CS 5
• Code Compression
the benefits of looping...
for (int i=0 ; i<4 ; ++i)
{
;
}
for loop
int i = 0;
while (i < 4)
{
++i;
}
while loop
more braces!
use reasonable
variable names
/*
*
*
*
*
*/
Style
introductory comment
Author:
Date:
Time:
Comment:
me!
9/26/04
d+(int)d/x minutes
The virtual lyricist
leave space before
blocks of code
class CS5App
{
public static void main(String[] args)
{
H.pl(“Enter your favorite mascot: ”);
align curly
braces that
correspond
String mascot = H.nw();
… more code here …
}
}
indent code evenly within
the surrounding braces
leave space between parts of
code that do different things
Comments ?
/*
*
*
*
*
*/
Author:
Date:
Time:
Comment:
if ( a < b
{
H.pl(“
}
introductory comment
me!
9/26/04
3 kiloseconds
Finding the max and min of 4 values
&&
a < c
&&
a < d )
Minimum is ” + a);
else if ( b < a && b < c &&
{
H.pl(“ Minimum is ” + b);
}
// see if a is minimal
comment at least
each block of code
b < d ) // see if b is minimal
very small blocks need only one comment for the entire group
Back inside the machine...
Shortcuts for changing variables:
int
i = 35;
i = i + 1;
i += 1;
++i;
i++;
Back inside the machine...
Shortcuts for changing variables:
int
i = 35;
i = i + 1;
i += 1;
++i;
all of these increment i by 1
i++;
Back inside the machine...
Shortcuts for changing variables:
int
i = 35;
i = i + 1;
i += 1;
++i;
all of these increment i by 1
int amoebas = 100000;
amoebas = amoebas * 2;
double hwToGo = 11.0;
hwToGo = hwToGo - 1;
long u235 = 10000000000000L;
u235 = u235 / 2;
i++;
Back inside the machine...
Shortcuts for changing variables:
int
i = 35;
i = i + 1;
i += 1;
++i;
i++;
all of these increment i by 1
int amoebas = 100000;
amoebas = amoebas * 2;
double hwToGo = 11.0;
hwToGo = hwToGo - 1;
long u235 = 10000000000000L;
u235 = u235 / 2;
amoebas *= 2;
hwToGo -= 1;
--hwToGo;
u235 /= 2;
An aside
What’s the difference between
++i
and
i++
Nothing -- when they are on their own!
?
An aside
What’s the difference between
++i
and
i++
?
Nothing -- when they are on their own!
When they are being used and set at the same time things change...
int i = 32;
int i = 32;
int x = ++i + 10;
int x = i++ + 10;
increments before use
increments after use
An aside
What’s the difference between
++i
and
i++
?
Nothing -- when they are on their own!
When they are being used and set at the same time things change...
int i = 32;
int i = 32;
int x = ++i + 10;
int x = i++ + 10;
x is 43
x is 42
i is 33
i is 33
increments before use
increments after use
Hw 4, Problem 1
Hw4Pr1) The improved math menu ...
Pair Programming Problem
Option # 4: unlimited max and min
Option # 3: function graphing
x = p/2
Option # 2: this integral
Option # 1: raw power
Option # 0: sequences
Hw4Pr2) Let’s Make a Deal !
Hw4Pr3) Let’s Make A LOT of Deals.
dx
x=0
the period of a pendulum with
length L and initial angle a
code != work
Sequencing items with a single piece of code
42
42
7
14
3
6
2
22
42
21
42
9
28
42
18
222
35
21
code != work
Sequencing items with a single piece of code
42
42
7
14
3
6
2
22
42
21
42
9
28
42
18
222
35
21
2222
42
42
42
Anatomy of a for loop
for ( int i = 0 ; i < 4 ; ++i )
{
H.pl(i);
}
Anatomy of a for loop
PART 1
PART 2
for ( int i = 0 ; i < 4 ; ++i )
{
PART 4
H.pl(i);
PART 3
}
Anatomy of a for loop
0
PART 1
PART 2
int i
for ( int i = 0 ; i < 4 ; ++i )
{
PART 4
H.pl(i);
PART 3
}
always
PART 1
create and initialize loop variable
PART 2
test to determine if we run the loop
PART 3
loop body is run if test is true
PART 4
update the loop variable
i<4
true
false
end
loop
code != work
Sequencing items with a single piece of code
42
42
7
14
3
6
2
22
42
21
42
9
28
42
18
222
35
21
2222
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
H.p( x + “ ” );
}
; ++i )
sharing with if
int x = 3;
for ( int i = 0 ; i < 6 ; ++i )
{
H.p( x + “ ” );
if (x%2 == 0)
else
}
“Quiz”
A
Print the output of these loops
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.
B
int c = 0;
for (int i=10 ; i>0 ; i/=2 )
{
H.p( i + “ ” );
c++;
}
H.pl(“c is ” + c);
C
int s = 0;
for (int i = 1 ; i < 5 ; ++i)
{
H.p( i + “ ” );
s = s + i;
}
H.pl(“\ns is ” + s);
Write a loop to print this sequence:
Write a loop to print this sequence:
9 terms total
9 terms total
0 1 2 3 6 7 14 15 30
Hint: Use a for loop
with an if inside it!
2 22 222 2222 ...
“Quiz”, part 2
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...
(1) Birth (of sum and i)
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...
(1) Birth (of sum and i)
int sum = 0;
for ( int i = 1 ; i < 5 ; ++i )
{
(2) Growth
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...
(1) Birth (of sum and i)
int sum = 0;
for ( int i = 1 ; i < 5 ; ++i )
{
(2) Growth
sum = sum + i;
}
H.pl(“sum is ” + sum);
int sum = 0;
for ( int i = 0 …
(3) Death (of i)
but sum lives on…
Why will java complain about this ?!?
Variables: a life story...
(1) Birth (of sum and i)
int sum = 0;
for ( int i = 1 ; i < 5 ; ++i )
{
(2) Growth
sum = sum + i;
}
H.pl(“sum is ” + sum);
sum = 0;
for ( int i = 0 …
(3) Death (of i)
but sum lives on…
reuse is OK
recreation 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
At the top of a CS 5 placement project file …
//
//
//
//
//
//
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
{
...
Extreme Looping
Java’s last and least built-in variable type: boolean
H.pl(“It keeps on”);
“while”
block
while ( true )
{
H.pl(“going and”);
}
Extreme Looping
Java’s last and least built-in variable type: boolean
H.pl(“It keeps on”);
“while”
block
while ( true )
{
H.pl(“going and”);
}
note what’s
NOT here!
Extreme Looping with while
No variable or expression is needed!
H.pl(“It keeps on”);
worry later about
how to escape !
while ( true )
{
H.pl(“going and”);
int escape = H.randInt(1,100);
if (escape == 100)
{
break;
here is how to
}
quit – use break !
}
“User – friendly” code
long 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” code
long 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();
same
as
before
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!
Monty Hall
Let’s make a deal ’63-’86
inspiring the “Monty Hall paradox”
Hw4Pr2) The Virtual Monty Hall
Sept. 1990
The two Monte Carlos
Making random
numbers work
for you!
Monte Carlo casino,
Monaco
• math hw
• physics hw
• cs hw
• Hum hw
Monte Carlo methods, Math/CS
Monte Carlo Monty Hall
Suppose you always switch to the other door...
What are the chances that you will win the car ?
Run it (randomly) 1000 times and see!
Hw4Pr3) Monte Carlo Monty Hall
Monty Hall program design
top-down software engineering
HW4PR3) Virtual Monty Hall
while (true) // program skeleton via short comments
{
Detailed design this
Friday in recitation…
}
Monte Carlo in action
Suppose you roll two dice.
What are the chances that you roll doubles?
set up a variable to count the
number of doubles rolled
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;
}
1000 times
one roll of the dice
count the number
of doubles rolled
}
H.pl(“We rolled ” + doublesCount + “ doubles.”);
Summary
statements and shortcuts for changing variables
x *= 10;
num += 10;
multiply x by 10
increase num by 10
for loop examples
for (int i=12 ; i>=0 ; i-=2)
{
H.p( i + “ ” );
}
prints 12 10 8 6 4 2 0
++i;
i++;
increase i by 1
i--;
decrease i by 1
int x = 3;
for (int i=0 ; i<9 ; ++i)
{
H.p( x + “ ” );
x = x + 12;
}
prints 3 15 27 39 51 63 75 87 99
while loop examples
continues until the user types “no”
--i;
while ( true )
{
String s = H.nw();
if (s.equals(“no”))
break;
}
Lab Today
N-Z
all others
welcome!
• I’d suggest starting by writing the for loops in Hw4Pr1
use loops to print
these sequences
10 15 20 25 30 35 40 45 50 55 60 65
11 22 33 44 55 66 77 88 99 110 121
1 2 4 8 16 32 64 128 256 512 1024 2048
0 3 9 12 36 39 117 120 360 363 1089
1 22 333 4444 55555 666666 7777777 88888888
print the sum of the first four sequences, too …
Hw4Pr1) Improved Math Menu
Pair Programming Problem
• then move on to the more involved examples...
Hw4Pr2
Virtual Monty Hall (while)
Hw4Pr3
Monte Carlo Monty Hall (for)
Summary
statements and shortcuts for changing variables
x *= 10;
num += 10;
multiply x by 10
increase num by 10
for loop examples
for (int i=12 ; i>=0 ; i-=2)
{
H.p( i + “ ” );
}
prints 12 10 8 6 4 2 0
++i;
i++;
increase i by 1
i--;
decrease i by 1
int x = 3;
for (int i=0 ; i<9 ; ++i)
{
H.p( x + “ ” );
x = x + 12;
}
prints 3 15 27 39 51 63 75 87 99
while loop examples
continues until the user types “no”
--i;
while ( true )
{
String s = H.nw();
if (s.equals(“no”))
break;
}
“Quiz”
Names:
Print the output of these loops:
A
for (int i = 10 ; i > 0 ; i+=1 )
{
H.p( i + “ ” );
}
B
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
C
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
Write a loop to print this sequence:
Write a loop to print this sequence:
9 terms total
9 terms total
0 1 2 3 6 7 14 15 30
Hint: Use a for loop
with an if inside it!
0 00 000 0000 ...
“Quiz”, part 2
Hint: Use a for loop
with a for loop inside it!
for (int i = 10 ; i > 0 ; i = i-2)
{
prints
H.p( i + “ ” );
}
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
A
B
prints
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
prints
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
C
for (int i = 10 ; i > 0 ; i = i-2)
{
prints
H.p( i + “ ” );
}
A
10 8 6 4 2
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
B
prints
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
prints
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
C
for (int i = 10 ; i > 0 ; i = i-2)
{
prints
H.p( i + “ ” );
}
10 8 6 4 2
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
prints
10 5 2 1 0
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
prints
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
for (int i = 10 ; i > 0 ; i = i-2)
{
prints
H.p( i + “ ” );
}
A
10 8 6 4 2
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
B
prints
10 5 2 1 0
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
prints
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
1 2 3 4
s is 10
C
9 terms total
Write a loop to print this sequence:
0 1 2 3 6 7 14 15 30
i=1
i=3
i=5
i=7
int x = 0;
for (int i=0 ; i<9 ; ++i)
{
H.p( x + “ ” );
if ( i%2 == 0 )
{
x = x + 1;
}
else
{
x = x * 2;
}
}
shorter?
9 terms total
Write a loop to print this sequence:
0 1 2 3 6 7 14 15 30
i=1
i=3
int x = 0;
for (int i=0 ; i<9 ; ++i)
{
H.p( x + “ ” );
if ( i%2 == 0 )
++x;
else
x *= 2;
}
ifs and elses have one-line bodies
(“blocks”) if no curly braces are used
i=5
i=7
9 terms total
Write a loop to print this sequence:
0
00
i=3
000
0000
...
for (int i=1 ; i<10 ; ++i)
{
for (int j=1 ; j<=i ; ++j)
{
H.p(0);
}
H.p(“ ”);
}
shorter?
9 terms total
Write a loop to print this sequence:
0
00
i=3
000
for (int i=1 ; i<10 ; ++i)
{
for (int j=1 ; j<=i ; ++j)
H.p(0);
H.p(“ ”);
}
ifs and elses have one-line bodies
(“blocks”) if no curly braces are used
0000
...
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
H.p( x + “ ” );
sum = sum + x;
}
H.pl(“sum is ” + sum);
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
H.pl(“sum is ” + sum);
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
(3) Death (of x)
H.pl(“sum is ” + sum);
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
(3) Death (of x)
H.pl(“sum is ” + sum);
int sum = 0;
for … next loop here …
Why will java complain about this ?!?
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
(3) Death (of x)
H.pl(“sum is ” + sum);
sum = 0;
for … next loop here …
You can reuse
But you can’t redeclare !
What’s this all for ?
Program for factorial
input: an integer n
output: 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”);
worry later about
how to escape !
while ( true )
{
H.pl(“going and”);
int escape = H.randInt(1,100);
if (escape == 100)
{
break;
here is how to
}
quit – use break !
}
“User – friendly” code
long 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” code
long 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();
same
as
before
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!
Monty Hall
Let’s make a deal ’63-’86
inspiring the “Monty Hall paradox”
Sept. 1990
Monte Carlo Monty Hall
Suppose you always switch to the other door...
What are the chances that you will win the car ?
Run it (randomly) 1000 times and see!
Hw4Pr3) Monte Carlo Monty Hall
The two Monte Carlos
Making random
numbers work
for you!
Monte Carlo casino,
Monaco
• math hw
• physics hw
• cs hw
• Hum hw
Monte Carlo methods, Math/CS
Summary
statements and shortcuts for changing variables
x *= 10;
num += 10;
multiply x by 10
increase num by 10
for loop examples
for (int i=12 ; i>=0 ; i-=2)
{
H.p( i + “ ” );
}
prints 12 10 8 6 4 2 0
++i;
i++;
increase i by 1
i--;
decrease i by 1
int x = 3;
for (int i=0 ; i<9 ; ++i)
{
H.p( x + “ ” );
x = x + 12;
}
prints 3 15 27 39 51 63 75 87 99
while loop examples
continues until the user types “no”
--i;
while ( true )
{
String s = H.nw();
if (s.equals(“no”))
break;
}
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?
set up a variable to count the
number of doubles rolled
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;
}
1000 times
one roll of the dice
count the number
of doubles rolled
}
H.pl(“We rolled ” + doublesCount + “ doubles.”);
Lab Today
N-Z
and any others…
• I’d suggest starting by writing the for loops in Hw4Pr1
use loops to print
these sequences
10 15 20 25 30 35 40 45 50 55 60 65
11 22 33 44 55 66 77 88 99 110 121
1 2 4 8 16 32 64 128 256 512 1024 2048
0 3 9 12 36 39 117 120 360 363 1089
1 22 333 4444 55555 666666 7777777 88888888
print the sum of just the first four sequences, too …
• then move on to the more involved examples...
Hw4Pr2
Virtual Monty Hall (while)
Hw4Pr3
Monte Carlo Monty Hall (for)
Hw4, Pr1, Option 4: random sums
See the Improved Moth Menu for working example code at www.cs.hmc.edu/~dodds/cs5
current code: 50000 random numbers
current plot: 50000 random numbers
case 4:
{
Histogram h = new Histogram();
for (int i=0 ; i<50000 ; ++i)
h.addPoint(Math.random());
outerFrame.updateSize();
break;
}
min x is ~0
Your task:
plot sums of random numbers
max x is ~1
Variables: a life story...
for ( int i = 0 ; i < 6 ; ++i )
{
(1)
int x = 1;
H.out.print( x + “ ” );
x = x*3;
(2)
}
Birth (of x and i)
Growth
(3) Death
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
(1) Birth (of x and i)
(3) Death
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
(2) Growth
(3) Death
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Variables: a life story...
for ( int i = 0 ; i < 6 ; ++i )
{
(1)
int x = 1;
H.out.print( x + “ ” );
x = x*3;
(2)
}
Birth (of x and i)
Growth
(3) Death
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Variables: a life story...
for ( int i = 0 ; i < 6 ; ++i )
{
(1)
int x = 1;
H.out.print( x + “ ” );
x = x*3;
(2)
}
Birth (of x and i)
Growth
(3) Death
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Back inside the machine...
Shortcuts for changing variables:
int
i = 33;
i = i + 1;
i += 1;
++i;
i++;
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
1
0
initialization statement
2
the “for”
block
test
variable 3
updates
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
#0 - create and initialize loop variables
#1 - check the test condition
if false, stop looping & jump past the “for” block
if true, continue looping
#2 - execute all of the code in the “for” block
#3 - update loop variables as desired; goto #1
0
int i
Anatomy of a for loop
initialization statement
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
#0 - create and initialize loop variables
0
int i
Anatomy of a for loop
test
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
#0 - create and initialize loop variables
#1 - check the test condition
if false, stop looping & jump past the “for” block
if true, continue looping
0
int i
the “for”
block
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
if false, stop looping & jump past the “for” block
if true, continue looping
output
#2 - execute all of the code in the “for” block
i is 0
1
int i
Anatomy of a for loop
variable
updates
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
#0 - create and initialize loop variables
#1 - check the test condition
if false, stop looping & jump past the “for” block
if true, continue looping
output
#2 - execute all of the code in the “for” block
#3 - update loop variables as desired; goto #1
i is 0
Execution of a for loop
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
output:
Execution of a for loop
0
int i
before
continue looping if true
1
start
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
output:
i is 0
int i
after
Execution of a for loop
1
int i
before
continue looping if true
2
start
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
output:
i is 0
i is 1
int i
after
Execution of a for loop
2
int i
before
continue looping if true
3
start
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
output:
i is 0
i is 1
i is 2
int i
after
Execution of a for loop
8
int i
before
continue looping if true
9
start
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
output:
i is 0
i is 1
i is 2
…
i is 8
int i
after
Execution of a for loop
8
int i
before
continue looping if true
9
start
for ( int i = 0 ; i < 9 ; ++i )
{
H.out.println(“i is ” + i);
}
jump to end of for loop if false
output:
i is 0
i is 1
i is 2
…
i is 8
int i
after
Monty Hall
Let’s make a deal ’63-’86
inspiring the “Monty Hall paradox”
Sept. 1990
Monte Carlo
Monte Carlo casino,
Monaco
Monte Carlo methods, Math/CS
Estimating a value (usually a probability) by
playing an appropriate game over and over.
“Quiz”
Names:
Print the output of these loops:
A
for (int i = 10 ; i > 0 ; i = i-2)
{
H.p( i + “ ” );
}
B
int i = 20;
while (i > 0)
{
i /= 2;
H.p( i + “ ” );
}
C
int s = 0;
for (int x = 1 ; x < 5 ; ++x)
{
H.p( x + “ ” );
s = s + x;
}
H.pl(“\ns is ” + s);
Write a loop to print this sequence:
Write a loop to print this sequence:
9 terms total
9 terms total
0 1 2 3 6 7 14 15 30
Hint: Use a for loop
with an if inside it!
0 00 000 0000 ...
“Quiz”, part 2
Hint: Use a for loop
with a for loop inside it!
“Quiz”, part 2
Hw4Pr1) Option #1: sequences
What code (using for) will print 0 1 2 3 6 7 14 15 30
9 terms total
0 1 2 3 6 7 14 15 30
Mixing it up...
What code (using for) will print
Hw4Pr1) Option #1: sequences
0
00
000
9 terms total
0000…
User - friendly code
boolean 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 )
{
(1)
int x = 1;
H.p( x + “ ” );
x = x*3;
(2)
}
Birth (of x and i)
Growth
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Variables: a life story...
for ( int i = 0 ; i < 6 ; ++i )
{
(1)
int x = 1;
H.p( x + “ ” );
x = x*3;
(2)
}
Birth (of x and i)
Growth
(3) Death
A variable’s scope is the block of code in which it is declared.
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...”);
9 terms total
Write a loop to print this sequence:
0
00
i=3
000
0000
...
for (int i=1 ; i<10 ; ++i)
{
for (int j=1 ; j<=i ; ++j)
{
H.p(0);
}
H.p(“ ”);
}
shorter?
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
(3) Death (of x)
H.pl(“sum is ” + sum);
A variable’s scope is the block of code in which it is declared.
A variable only exists until the closing curly brace of its scope...
Variables: a life story...
(1) Birth (of sum and x)
int sum = 0;
for ( int x = 0 ; x < 6 ; ++x )
{
(2) Growth
H.p( x + “ ” );
sum = sum + x;
}
(3) Death (of x)
H.pl(“sum is ” + sum);
sum = 0;
for … next loop here …
You can reuse
But you can’t redeclare !
What’s this all for ?
Program for factorial
input: an integer n
output: 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”);
worry later about
how to escape !
while ( true )
{
H.pl(“going and”);
double r = Math.random();
if (r > 0.99)
{
break;
here is how to
}
quit – use break !
}
“User – friendly” code
long 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.