Date post: | 19-Dec-2015 |
Category: |
Documents |
View: | 213 times |
Download: | 0 times |
COMP 14Introduction to Programming
Mr. Joshua StoughFebruary 16, 2005
Monday/Wednesday 11:00-12:15
Peabody Hall 218
Announcements
• Mid-Term Exam - March 9– covers Chapters 1-5– look at previous mid-term, homework
exercises, in-class exercises, words in bold print in textbook
• Monday– sit with your recitation group– each group should have laptop, textbook,
and lab manual
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
Questions
What type of while loop should be used?
1. Read every line in a file until the number -99 is read.
2. Read every line in a file where the length of the file is unknown.
3. Make sure that the user enters a lowercase letter.
4. Print the even numbers between 0 and 50.
sentinel-controlled
EOF-controlled
input validation
counter-controlled
The while Loop
while (expression)statement
The while Loop
final int LIMIT = 3;
int count = 0;
while (count < LIMIT) {
System.out.println (count);
count++;
}
System.out.println (“All done!”);
booleancondition
loopbodyupdate
initialization
Output:012All done!
In-Class Exercise
Write a while loop that prints2468
int i = 2;while (i <= 8) {
System.out.println (i);i += 2;
}
int i = 1;while (i <= 4) {
System.out.println (i*2);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?
int count = 0, num;num = Integer.parseInt(keyboard.readLine());while (num < 0) {System.out.println (num);num = Integer.parseInt(keyboard.readLine());count++;
}
num
Today in COMP 14
• The for loop• The do...while loop• break and continue• Nested loops
• Textbook Reference: Ch 5 (pgs. 229-247)
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 LoopExecution
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 LoopSyntax
for ( initialization; condition; update ) { loop body;}
Reservedword
The initializationis executed once
before the loop begins
The loop body isexecuted until the
condition becomes false
The update portion is executed at the end of each iterationThe 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 LoopExample
final int LIMIT = 3;
int count;
for (count=0; count<LIMIT; count++) {
System.out.println (count);
}
System.out.println (“All done!”);
booleancondition
loop bodyupdate
initialization
Output:012All 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*
HelloHelloHelloHelloHello*
*
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 Exercisefor vs. while Loopsfinal 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.
Output:0369121518
final int MAX = 20;int i = 0;while (i < MAX) {
System.out.println (i);i += 3;
}
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 LoopSyntax
do{ loop body;}while ( condition );
do andwhile arereserved
words
The loop body is executed once initially,and then the condition is evaluated
The loop body is executed repeatedlyuntil 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 LoopExamplefinal int LIMIT = 3;
int count = 0;
do {
System.out.println (count);
count++;
} while (count < LIMIT);
System.out.println (“All done!”);
booleanconditio
n
loopbodyupdat
e
initialization
Output:012All done!
Comparing while and do...while
while Loop
final int LIMIT=3;int count = 0;
while (count < LIMIT) {System.out.println (count);count++;
}
System.out.println (“All done!”);
do...while Loop
final int LIMIT=3;int count = 0;
do {System.out.println (count);count++;
} while (count < LIMIT);
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 ExerciseThe 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
y0
0
Output:
1 2
004616
23
4
45
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 = 0i = 1i =
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 Exampleint i;for (i=0; i<5; i++) {
System.out.print ("i = ");if (i == 2) {
continue;}System.out.println (i);
}
i = 0i = 1i = i = 3i = 4
int i=0;while (i<5) {
System.out.print ("i = ");if (i == 2) {
continue;}System.out.println (i);i++;
}
i = 0i = 1i = 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 Examplefor (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
(outside / header)
number of loop body
executions
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
4 parts of every loop
1. initialization2. condition3. loop body4. update
Orderwhile and for
1. initialization2. condition3. loop body4. update
do...while1. initialization2. loop body3. update4. 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.
• Allow the user to enter invalid input and prompt them for valid input.
• You do not have to use letters for selecting the shapes.
• Start early!
Program 3Break Program into Smaller Steps1. Print out welcome message, options, and
directions to user2. 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 3Break Program into Smaller Steps6. Write code that decides if the
computer or the user won7. 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
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);
Print a random number in {-1, 0, 1}.
System.out.println ((int) (Math.random() * 3) - 1);
In-Class ExerciseRandom
Write a code fragment to choose a random number in {0, 1, 2, 3}.
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
sample = (int) (Math.random() * 4);
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;
}
Next Time in COMP 14
• Programming Session
• Sit with your recitation group
• Each group should have a laptop, textbook, and lab manual