Title: Loops (cont.)
1Loops (cont.)
2Loop Statements
while ( condition ) statement
- while statement
- do statement
- for statement
do statement list while ( condition )
for ( initialization condition increment )
statement
3Flowchart of a while Loop
while ( condition ) statement
4Example
System.out.print( Enter a month (1 to 12)
) int month scan.nextInt() while (month lt 1
month gt 12) System.out.println( month
is not a valid month. ) System.out.print(
Enter a month (1 to 12) ) month
scan.nextInt()
// set initial value of month so that the while
condition // below is false initially int month
-1 while (month lt 1 month gt 12)
System.out.print( Enter a month (1 to 12) )
month scan.nextInt()
5The do Statement Syntax
do statement while ( condition )
The statement is executed once initially, then
the condition is evaluated
The statement is repetitively executed until the
condition becomes false
6Flowchart of a do Loop
do statement while ( condition )
7Comparing the while and do Loops
- A do loop is similar to a while loop, except
that the condition is evaluated after the body of
the loop is executed - Therefore the body of a do loop will execute at
least once
8Example
int month // no need to initialize month do
System.out.print( Enter a month (1 to 12) )
month scan.nextInt() while (month lt 1
month gt 12) // beginning of the next statement
9The for Statement Syntax
for ( initialization condition increment )
statement
10The for Statement Syntax
- Each expression in the header of a for loop is
optional - if the initialization is left out, no
initialization is performed - if the condition is left out, it is always
considered to be true - if the increment is left out, no increment
operation is performed
11Flowchart of a for loop
for ( initialization condition increment )
statement
12The for Statement
for ( initialization condition increment )
statement
- A for loop is equivalent to the following while
loop structure
initialization while ( condition )
statement increment
13The for Statement Example
int sum 0 for (int counter 1 counter lt
max counter) sum counter // beginning of
the next statement
Establish initial value of control variable.
int counter 1
Determine if final value of control variable has
been reached.
true
sum counter
counter lt max
counter
Increment the control variable.
false
Body of loop (this may be multiple statements)
14Summary Loop Statements Syntax
while ( condition ) statement
- while statement
- do statement
- for statement
do statement list while ( condition )
for ( initialization condition increment )
statement
15Comments about Loop Statements
- Choosing which loop statement to use will depend
on the specific situation and personal taste - Checking and updating the condition
- in most cases, the body of a loop must eventually
make the condition false - if not, it is an infinite loop, which will
execute until the user interrupts the program - Ctrl-C in command line
- this is a common type of logical error, and you
should always double check to ensure that your
loops will terminate normally - pay attention to the condition to avoid an off
by 1 problem
16Designing a Loop A (Rough) Template
- Think of state (captured by variables) that you
need to keep track across multiple iterations - e.g., counter, sum
- e.g., boolean variables thisRoundIsOver,
canBeDivided - Initialize state (variables)
- Inside the loop
- process
- the processing may depend on the current state
- update state
- e.g., increase the counter, add to sum, set the
flag - Termination condition in general, it is a
boolean expression involving the state variables
17Example Check if a Number is Prime
// check if a positive integer n is
prime boolean canBeDivided false for (int i
2 i lt n !canBeDivided i) if (n i
0) canBeDivided true if
(!canBeDivided) System.out.println (n is
not a prime!) else System.out.println (n
is a prime!)
18Example Reverse a Number
number
reverse
1
2
5
4
3
6
7
7
6
3
4
5
2
1
reverse
number
1
2
5
4
3
7
6
The state is captured by number and reverse.
19Example Reverse a Number
reverse
number
1
2
4
3
7
6
int intReverse (int number)
int reverse , lastDigit
reverse 0 while (number gt 0)
lastDigit number 10 reverse
reverse 10 lastDigit
number number / 10
20Example Reverse a Number
reverse
number
1
2
4
3
7
6
5
reverse 0 while (number gt 0) lastDigit
number 10 reverse reverse 10
lastDigit number number / 10
21Example Play Games
// initialize global state variables // such as
statistics boolean userQuits false do //
initialize state variables for one game //
such as number of guesses allowed boolean
thisRoundIsOver false do // get
user input // process input, update states
// determine if thisRoundIsOver //
userQuits implies thisRoundIsOver while (
!thisRoundIsOver ) // update statistics of
preceding game while ( !userQuits ) // report
total statistics
22Using Break Loop-and-a-Half Idiom
Initialize total to zeroInitialize counter to
zero While (true) Input
next grade (possibly the sentinel) If
( the user has entered the sentinel)
break Add this grade into the
running total Add one to the grade
counter If the counter is not equal
to zero Set the average to the total
divided by the counter Print the
averageElse Print No grades were
entered
Initialize total to zeroInitialize counter to
zero Input the first grade (possibly the
sentinel) While (grade ! sentinel)
Add this grade into the running total
Add one to the grade counter Input
next grad (possibly the sentinel) If
the counter is not equal to zero Set the
average to the total divided by the counter
Print the averageElse Print No grades
were entered
23Exercise AverageGrade
- Write a program to compute the average of a
sequence of (numerical) student grades entered by
the user - If the user types something else than a number
between 0.0 and 4.0, the program should abort.
24Exercise Reverse a Number
- Write a program that outputs a reverse of the
positive integers the user types. - If the user types something else, the program
should abort.
25Exercise PalindromeTester
- Write a program to read in a sequence of strings
for each string, determine whether it is a
palindrome
26Exercise Stars
- Write a program to print a triangle formed by
-
-
-
- The program should read in the number of rows
from the user the row should be between 1 to 10
27Methods
28Methods
- A useful program can be long and contains many
statements - A method groups a sequence of statements and
should provide a well-defined, easy-to-understand
functionality - a method takes input, performs actions, and
produces output - Recall In Java, each method is defined within
specific class
29Method Declaration Header
- A method declaration begins with a method header
parameter list
method name
The parameter list specifies the type and name of
each parameter The name of a parameter in the
method declaration is called a formal argument
return type
properties
30Method Declaration Body
- The header is followed by the method body
31The return Statement
- The return type of a method indicates the type of
value that the method sends back to the calling
location - A method that does not return a value has a void
return type - The return statement specifies the value that
will be returned - Its expression must conform to the return type
32Calling a Method
- Each time a method is called, the values of the
actual arguments in the invocation are assigned
to the formal arguments
int num min (2, 3)
33Method Overloading
- A class may define multiple methods with the same
name---this is called method overloading - usually perform the same task on different data
types - Example The PrintStream class defines multiple
println methods, i.e., println is overloaded - println (String s)
- println (int i)
- println (double d)
-
- The following lines use the System.out.print
method for different data types - System.out.println ("The total is")
- double total 0
- System.out.println (total)
34Method Overloading Signature
- The compiler must be able to determine which
version of the method is being invoked - This is by analyzing the parameters, which form
the signature of a method - the signature includes the type and order of the
parameters - if multiple methods match a method call, the
compiler picks the best match - if none matches exactly but some implicit
conversion can be done to match a method, then
the method is invoke with implicit conversion. - the return type of the method is not part of the
signature
35Method Overloading
36More Examples
double tryMe ( int x ) return x 5
Which tryMe will be called?
tryMe( 1 ) tryMe( 1.0 ) tryMe( 1.0,
2) tryMe( 1, 2) tryMe( 1.0, 2.0)
double tryMe ( double x ) return x
.375
double tryMe (double x, int y) return x
y
37Variable Scoping
38Three variable types
- There are can be three types of variables in a
method - local variables
- those declared in the method
- formal arguments
- class variables
- those defined in the class but not in the method
39Example of Variable Types
public class Box private int length, width
public int widen (int extra_width)
private int temp1 size extra_width
public int lenghten (int extra_lenth)
private int temp2 size extra_length
- class variables
- formal arguments
- local variables
40Scope of Variables
public class Box private int length, width
public int widen (int extra_width)
private int temp1 size extra_width
public int lenghten (int extra_lenth)
private int temp2 size extra_length
- Class variables are valid in all methods of the
class - A formal argument is valid within its method
- Local variables are valid from the point of
declaration to the end of the enclosing block
41Two Types ofParameter Passing
- If a modification of the formal argument has no
effect on the actual argument, - it is call by value
- If a modification of the formal argument can
change the value of the actual argument, - it is call by reference
42Call-By-Value and Call-By-Reference in Java
- Depend on the type of the formal argument
- If a formal argument is a primitive data type, a
modification on the formal argument has no effect
on the actual argument - this is call by value, e.g. num1 min(2, 3)
- num2 min(x, y)
- If a formal argument is not a primitive data
type, an operation on the formal argument can
change the actual argument - this is call by reference
- more discussion in the later part of the course