Week04
- 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been copied and communicated to you by or
on behalf of Bond University pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
under the Act. Any further copying or communication of this
material by you may be the subject of copyright protection
under the Act.
- 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
the while loop
the do loop
the for loop
• The programmer should choose the right kind of
loop for the situation
- 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
• If the condition is true, the statement is
executed
• Then the condition is evaluated again, and if it is
still true, the statement is executed again until the
condition becomes false
• We use while loops when we cannot predict the
number of times the loop will execute, e.g.
•testing for bad user input
•processing input records from a database
- 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5
Logic of a while Loop
statement
true
false
condition
evaluated
- 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}
• If the condition of a while loop is false initially,
the statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
- 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7
How Often is the Body Run?
• If the condition of a while loop is false initially,
the statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
• Once inside the body of the while loop, if nothing
is done to modify the loop condition, we get an
infinite loop
- 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8
Infinite Loops
• The body of a while loop eventually must make
the condition false
• If not, it is called an infinite loop, which will
execute until the user interrupts the program
• This is a common logical error
• You should always double check the logic of a
program to ensure that your loops will terminate
normally
- 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9
Infinite Loops
• An example of an infinite loop:
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}
• This loop will continue executing until interrupted
(Control-C) or until an underflow error occurs
- 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10
Running Sum, Count, Max, Min
• In the Average program from Week 3's lab, we saw
how to keep a running count of the numbers
entered by the user
• We also kept a running sum of the numbers
entered. This allowed us to calculate the average
of the numbers entered
• The same idea can be used to calculate the
maximum and minimum of the numbers entered;
see Average2 from Week 4's lab
• We must start the running maximum small so that
the first number entered overwrites it
• The same thing goes for the running minimum
• Can you think of numbers which will break it?
- 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11
Nested Loops
• Similar to nested if statements, loops can be
nested as well
• That is, the body of a loop can contain another
loop
• For each iteration of the outer loop, the inner loop
iterates completely
• See PalindromeTester.java (page 235)
- 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
- 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13
The do Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition )
• The statement is executed once initially, and then
the condition is evaluated
• The statement is executed repeatedly until the
condition becomes false
- 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14
Logic of a do Loop
true
condition
evaluated
statement
false
- 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15
The do Statement
• An example of a do loop:
• The body of a do loop executes at least once
• See ReverseNumber.java (page 244)
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
- 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16
Comparing while and do
statement
true
falsecondition
evaluated
The while Loop
true
condition
evaluated
statement
false
The do Loop
- 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17
When to Use Do or While?
• Use a do loop when the loop body must be
executed at least once, e.g
• Get the user's input before we can tell that it is
invalid
• Use either of these two loop forms when the
number of times the loop must execute is
unknown
• When the number of iterations through the loop is
known in advance, you should use a for loop
- 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18
Looping N times, or over a range
• In many situations, you know in advance how many times
that you want to loop, e.g.
•Do something for every day in this month
• Alternatively, you need to loop over a range of values, e.g.
•Do some calculations for each possible age in the range 0
to 100 years old
• In these situations, we use the for loop.
• The for loop:
•has a loop counter, holding one value in the range each
time through the loop, and
•increments the loop counter for you
- 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19
The for Statement
• A for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is
executed at the end of each
iteration
- 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20
Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
- 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
- 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22
The for Statement
• An example of a for loop:
for (int count=1; count <= 5; count++)
System.out.println (count);
• In this example, count goes from 1 to 5 in steps of 1,
and the count value is printed out
• The initialization section can be used to declare a
variable
• Like a while loop, the condition of a for loop is tested
prior to executing the loop body
• Therefore, the body of a for loop will execute zero or
more times
- 23. © 2004 Pearson Addison-Wesley. All rights reserved 5-23
The for Statement
• The increment section can perform any calculation
• What does the above loop print out?
• A for loop is well suited for executing statements
a specific number of times that can be calculated
or determined in advance
• See Multiples.java (page 248)
• See Stars.java (page 250)
for (int num=100; num > 0; num -= 5)
System.out.println (num);
- 24. © 2004 Pearson Addison-Wesley. All rights reserved 5-24
Nested For Loops
• Just like other control structures in Java, for loops
can be nested inside other loops or if statements
• What does this code do?
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=20; cols++)
System.out.print(“*”);
System.out.println;
}
• Try it in the Java debugger and see
- 25. © 2004 Pearson Addison-Wesley. All rights reserved 5-25
Nested For Loops
• It's important here to remember to treat the outside
loop counter as constant
• Watch what happens when we use the outside
loop counter as a constant in the inner loop:
• What does this code do?
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=rows; cols++)
System.out.print(“*”);
System.out.println;
}
• Try it in the Java debugger and see
- 26. © 2004 Pearson Addison-Wesley. All rights reserved 5-26
Nested For Loops
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=rows; cols++)
System.out.print(“*”);
System.out.println;
}
• Note that the inner loop uses the value of the rows
variable to determine the number of stars to print
- 27. © 2004 Pearson Addison-Wesley. All rights reserved 5-27
Class Exercise
• Write a program to print out a multiplication table,
with columns 1 2 3 4 5 6 7 8 9 10, and rows 1 .. 10, e.g.
x 1 2 3 4 5 6 7 8
1 1 2 3 4 5 6 7 8
2 2 4 6 8 10 12 14 16
3 3 6 9 12 15 18 21 24
• Hint: we need 2 variables to multiply together. What
can we name them?
• Hint: do we need loops? How many loops?
• Hint: when do we print a newline?
• Suggestion: don't print the blue numbers to start with
- 28. © 2004 Pearson Addison-Wesley. All rights reserved 5-28
Class Exercise
• Modify the program to print out the row and
column labels. Include horizontal and vertical bars
if possible.
• Modify the program to ask the user for the upper
bound for the table size, instead of using 10.
• Modify the program to ensure that the user's input
is between 5 and 15.
- 29. © 2004 Pearson Addison-Wesley. All rights reserved 5-29
Program Development Tips
• Think about the problem BEFORE you start writing
code!!
• What variables will be needed, how will they
change over time?
• What control structures do you think you'll need:
IF, WHILE, DO, FOR, and where?
• Develop your program one bit at a time. Test what
you have written before adding new stuff.
• Use the debugger to show you what the code is
actually doing. Remember: a computer DWIS not
DWIW.
- 30. © 2004 Pearson Addison-Wesley. All rights reserved 5-30
Program Development Tips
• Use a top-down approach, e.g.
Get the input from the user, make sure it's between 5 and
10
Print out the heading (need a loop here, probably a FOR
loop as we know the table size)
We need a loop for each line, again a FOR loop
FOR each line
• We need another variable to be the column variable, and
we're going to need an inner loop now
• Do the multiplication inside the inner loop and print out the
result
• At the end of the line, i.e. when the inner loop has finished,
print out the newline
• Alternatively, if you know the code to write to do a
specific thing, then do it (bottom-up).
• You will usually do a bit top-down and a bit
bottom-up.
- 31. © 2004 Pearson Addison-Wesley. All rights reserved 5-31
Break and Continue
• Inside a loop body, the break command instantly
exits the loop and starts the code following the
loop.
• Inside a loop body, the continue command
instantly takes you to the top of the loop. Any
condition at the top of the loop is evaluated.
• The textbook suggests you should avoid these two
commands. I disagree.
• Example: ask user for number between 1 and 100.
If they enter something else, tell them that they are
stupid and ask again.
- 32. © 2004 Pearson Addison-Wesley. All rights reserved 5-32
The Break Command
int value;
while (true)
{
System.out.print(“Enter num 1-100: “);
value=scan.nextInt();
if ((value>=1) && (value<=100)
break;
System.out.println(“Idiot! Try again”);
}
• Note the loop looks like an infinite loop. But the
loop breaks when the user gets it right.
• Try doing the same with a normal WHILE or DO
loop