Transcript Sep 26

COMP 110
Introduction to Programming
Mr. Joshua Stough
September 26, 2007
Announcements
• Mid-Term Exam - W, Oct 17
– covers Chapters 1-7
– look at previous mid-term, homework exercises,
in-class exercises, words in bold print in textbook
Loops
• Allow us to repeat statements some number of times
• Must use a loop control variable
– controls how many times to loop
• 4 Parts to Every Loop
–
–
–
–
initialization - set loop control variable before condition
condition - when to stop
update - change to the loop control variable
body - actions to repeat
Typical Uses of Loops
• Repeat a section of code a specified number of
times - counter-controlled
• Repeat a section of code (reading input) until the a
specific value is read - sentinel-controlled
• Repeat a section of code (reading input) until a
valid value is entered - input validation
• Repeat a section of code (reading from a file) until
the end of the file is reached - EOF-controlled
• Repeat a section of code until a boolean variable
becomes false - flag-controlled
• WinPercentage.java
Questions
1.
2.
3.
4.
What type of while loop should be
used?
Read every line in a file until the number -99
is read.
sentinel-controlled
Read every line in a file where the length of
the file is unknown.
EOF-controlled
Make sure that the user enters a lowercase
letter.
input validation
Print the even numbers between 0 and 50.
counter-controlled
The while Loop
while (expression)
statement
The while Loop
final int LIMIT = 3;
boolean
int count = 0;
condition
initialization
while (count < LIMIT) {
System.out.println (count);
count++;
loop
}
body
update
System.out.println (“All done!”);
Output:
0
1
2
All done!
In-Class Exercise
Write a while loop that prints
2
int i = 2;
while (i <= 8) {
4
System.out.println
i += 2;
6
}
8
int i = 1;
while (i <= 4) {
System.out.println (i*2);
i++;
}
(i);
In-Class Exercise
Write a while loop that prints the odd
numbers between 0-100.
int i = 0;
while (i < 100) {
if ((i % 2) == 1) {
System.out.println (i);
}
i++;
}
int i = 1;
while (i <= 99) {
System.out.println (i);
i+=2;
}
Question
What is the loop control variable in the following
while loop?
num
int count = 0, num;
num = Integer.parseInt(keyboard.readLine());
while (num < 0) {
System.out.println (num);
num = Integer.parseInt(keyboard.readLine());
count++;
}
Today in COMP 110
• The for loop
• The do...while loop
• break and continue
• Nested loops
• Textbook Reference: Ch 5
The for Loop
• Specialized form of while loop
• Simplifies the writing of count-controlled loops
Basic Form:
for (initialization; condition; update)
{
statement(s);
}
The for Loop
Execution
1. initial statement
executes
2. loop condition
evaluated
3. If loop condition
evaluates to true,
execute for loop
statement and execute
update statement
4. Go back to step 2 and
repeat until loop
condition is false
The for Loop
Syntax
Reserved
word
The initialization
is executed once
before the loop begins
The loop body is
executed until the
condition becomes false
for ( initialization; condition; update ) {
loop body;
}
The update portion is executed at the end of each iteration
The condition-loop body-update cycle is executed repeatedly
for vs. while
A for loop is functionally equivalent to
the following while loop structure:
initialization;
while ( condition )
{
loop body;
update;
}
The for Loop
Example
final int LIMIT = 3;
int count;
initialization
boolean
condition
Output:
0
1
2
All done!
for (count=0; count<LIMIT; count++) {
System.out.println (count);
update
}
loop body
System.out.println (“All done!”);
Comparing while and for
While Loop
final int LIMIT=3;
int i = 0;
while (i < LIMIT) {
System.out.println (i);
i++;
}
System.out.println
(“All done!”);
For Loop
final int LIMIT=3;
int i;
for (i=0; i<LIMIT; i++) {
System.out.println (i);
}
System.out.println
("All done!");
The for Loop
• Like a while loop, the condition of a for
statement is tested prior to executing the
loop body
• The body of a for loop will execute zero or
more times
• It is well suited for executing a loop a specific
number of times that can be determined in
advance
• Anything you can do in a for loop, you can
do in a while loop
The for Loop
• Does not execute if initial condition is false
• Update expression changes value of loop
control variable, eventually making it false
• If loop condition is always true, result is an
infinite loop
• for statement ending in semicolon is
empty; does not affect program
for (count=0; count<LIMIT; count++);
Examples
for (i=1; i<=5; i++) {
System.out.println ("Hello");
System.out.println ("*");
}
for (i=1; i<=5; i++)
System.out.println ("Hello");
System.out.println ("*");
for (i=1; i<=5; i++);
System.out.println ("*");
*
Hello
Hello
Hello
Hello
Hello
*
Hello
*
Hello
*
Hello
*
Hello
*
Hello
*
Multiples.java Example
• Ask the user for a positive number
• Ask the user for a limit
• Print all of the multiples of the positive
number up to limit
• What happens if the user enters a
negative number?
In-Class Exercise
for vs. while Loops
final int MAX = 20;
int i;
for (i = 0; i<MAX; i+=3) {
System.out.println (i);
}
•
•
Predict the output
Translate this to a while loop.
final int MAX = 20;
int i = 0;
while (i < MAX) {
System.out.println (i);
i += 3;
}
Output:
0
3
6
9
12
15
18
The do…while Loop
• Statements executed first, then expression
evaluated
• Statement(s) executed at least once then
continued if expression is true
• Basic Form:
do {
statement(s);
} while (expression);
The do...while Loop
Syntax
do and
while are
reserved
words
do
{
loop body;
}
while ( condition );
The loop body is executed once initially,
and then the condition is evaluated
The loop body is executed repeatedly
until the condition becomes false
do…while Loop
(Post-test Loop)
do {
statement(s);
} while (expression);
The do...while Loop
• Like a while loop, but its condition is at
the end of the loop
• Loop body always executes at least
once
• Must also be checked for termination
(not an infinite loop)
• Anything you can do with a
do...while loop, you can do with a
while loop
The do...while Loop
Example
final int LIMIT = 3;
int count = 0;
initialization
do {
System.out.println (count);
count++;
loop
} while (count < LIMIT);
body
update
System.out.println (“All done!”);
boolean
condition
Output:
0
1
2
All done!
Comparing while and
do...while
while Loop
do...while Loop
final int LIMIT=3;
int count = 0;
final int LIMIT=3;
int count = 0;
while (count < LIMIT) {
System.out.println
(count);
count++;
}
do {
System.out.println
(count);
count++;
} while (count < LIMIT);
System.out.println
(“All done!”);
System.out.println
("All done!");
while vs. do...while
i = 11;
while (i <= 10) {
System.out.print (i + " ");
i += 5;
}
System.out.println();
i = 11;
do {
System.out.print (i + " ");
i += 5;
} while (i <= 10);
System.out.println();
[blank line]
11
In-Class Exercise
The do...while Loop
int x = 0, y = 0;
do {
System.out.println (x*y);
if (y < x) {
y += 2;
}
x++;
} while (x < 5);
• Predict the output of the loop
x
0
1
2
3
4
5
y
0
2
4
Output:
0
0
4
6
16
break Statements
• Used to exit early from a loop
• Used to skip remainder of switch
structure
• Can be placed within if statement of a
loop
– If condition is met, loop exited immediately
break Example
int i;
for (i=0; i<5; i++) {
System.out.print ("i = ");
if (i == 2) {
break;
}
System.out.println (i);
}
i = 0
i = 1
i =
continue Statements
• Used in while, for, and do...while
structures
• When executed in a loop, the remaining
statements in the loop are skipped; proceeds
with the next iteration of the loop
• When executed in a while/do…while
structure, expression evaluated immediately
after continue statement
• In a for structure, the update statement is
executed after the continue statement; then
the loop condition executes
continue Example
int i;
for (i=0; i<5; i++) {
System.out.print ("i = ");
if (i == 2) {
continue;
}
System.out.println (i);
}
int i=0;
while (i<5) {
System.out.print ("i = ");
if (i == 2) {
continue;
}
System.out.println (i);
i++;
}
i
i
i
i
=
=
=
=
0
1
i = 3
4
i = 0
i = 1
i = i = i = ...
(infinite loop)
Nested Control Structures
• Provides new power, subtlety, and
complexity
• if, if…else, and switch structures
can be placed within while loops
• for loops can be found within other
for loops
– each time through the outer loop, the inner
loop goes through its full set of iterations
Nested Control Structures
Example
for (int row = 1; row <= 5; row++) {
for (int star = 1; star <= row; star++) {
System.out.print(“*”);
}
System.out.println();
Output:
}
• Can't use the variable row
outside the outer for loop.
• Can't use the variable star
outside the inner for loop.
*
**
***
****
*****
Flips.java Example
• Flip a coin 5 times
– choose a random number
• Print the total number of heads and tails
Loop Features
loop
initialization number of
loop body
(outside /
executions
header)
update
(inside /
header)
conditional
(beginning /
end)
while outside
0 or more
inside
beginning
do
outside
1 or more
inside
end
for
header
0 or more
header
beginning
Choosing a Loop Structure
• while
– you don't know how many times to execute the
loop body
• do...while
– you don't know how many times to execute the
loop body, but it's at least once
• for
– you know exactly how many times to execute the
loop body
Loops
Order
4 parts of every loop
1.
2.
3.
4.
initialization
condition
loop body
update
while and for
1.
2.
3.
4.
initialization
condition
loop body
update
do...while
1.
2.
3.
4.
initialization
loop body
update
condition
Program 3
• Rock-Paper-Scissors-Spock-Lizard
– variation on Rock-Paper-Scissors
• Have the computer choose one of the 5
shapes.
– Hint: Math.random
• Ask the user to choose one of the 5 shapes
or 'q' to quit.
• Decide who wins.
• After the user quits, print out a tally of the
user wins, losses, and ties.
Program 3
• You must print the title of the game.
• You must make sure the user knows
what to enter to choose a particular
shape.
• Start early!
Program 3
Break Program into Smaller Steps
1. Print out welcome message, options, and
directions to user
2. Write a loop that allows the user to enter a
character and end the loop if the user
enters 'q' (or 'Q')
3. Write code that will print out the shape
(rock, paper, ...) based on what the user
entered
4. Write code that will make the computer
choose a shape
5. Write code that will print out what shape the
computer chose
Program 3
Break Program into Smaller Steps
6. Write code that decides if the computer or
the user won
7. Write code that will keep up with the
number of wins, losses, and ties for the user
8. Write code that will print out the number of
wins, losses, and ties after the user
chooses to quit
Math.random Example
Print a random number in {-1, 0, 1}.
double randomNum;
int sample012;
// Math.random() will return [0.0, 1.0)
randomNum = Math.random();
// sample012 will be {0, 1, 2}
sample012 = (int) (randomNum * 3);
// print out {-1, 0, 1}
System.out.println(sample012 - 1);
System.out.println ((int) (Math.random() * 3) - 1);
In-Class Exercise
Random
Write a code fragment to choose a
random number in {0, 1, 2, 3}.
sample = (int) (Math.random() * 4);
Print 'A' if the number chosen is 0, 'B' if
the number is 1, 'C' if the number is 2,
and 'D' if the number is 3.
– Hint: a switch statement would be
appropriate here
int sample;
// sample will be {0, 1, 2, 3}
sample = (int) (Math.random() * 4);
switch (sample) {
case 0:
System.out.println("A");
break;
case 1:
System.out.println("B");
break;
case 2:
System.out.println("C");
break;
case 3:
System.out.println("D");
break;
}