Loops (cont.) - PowerPoint PPT Presentation

About This Presentation
Title:

Loops (cont.)

Description:

set initial value of month so that the while condition // below is false initially ... The statement is executed once initially, then the condition is evaluated ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 43
Provided by: deptinform
Learn more at: https://ics.uci.edu
Category:
Tags: condition | cont | loops

less

Transcript and Presenter's Notes

Title: Loops (cont.)


1
Loops (cont.)
2
Loop Statements
while ( condition ) statement
  • while statement
  • do statement
  • for statement

do statement list while ( condition )
for ( initialization condition increment )
statement
3
Flowchart of a while Loop
while ( condition ) statement
4
Example
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()
5
The 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
6
Flowchart of a do Loop
do statement while ( condition )
7
Comparing 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

8
Example
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
9
The for Statement Syntax
for ( initialization condition increment )
statement
10
The 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

11
Flowchart of a for loop
for ( initialization condition increment )
statement
12
The for Statement
for ( initialization condition increment )
statement
  • A for loop is equivalent to the following while
    loop structure

initialization while ( condition )
statement increment
13
The 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)
14
Summary Loop Statements Syntax
while ( condition ) statement
  • while statement
  • do statement
  • for statement

do statement list while ( condition )
for ( initialization condition increment )
statement
15
Comments 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

16
Designing 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

17
Example 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!)
18
Example 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.
19
Example 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
20
Example 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
21
Example 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
22
Using 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
23
Exercise 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.

24
Exercise 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.

25
Exercise PalindromeTester
  • Write a program to read in a sequence of strings
    for each string, determine whether it is a
    palindrome

26
Exercise 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

27
Methods
28
Methods
  • 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

29
Method 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
30
Method Declaration Body
  • The header is followed by the method body

31
The 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

32
Calling 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)
33
Method 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)

34
Method 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

35
Method Overloading
36
More 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
37
Variable Scoping
38
Three 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

39
Example 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

40
Scope 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

41
Two 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

42
Call-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
Write a Comment
User Comments (0)
About PowerShow.com