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

Preview:

Citation preview

Loops (cont.)

Loop Statements

while statement

do statement

for statement

while ( condition ) statement;

do { statement list;} while ( condition );

for ( initialization ; condition ; increment ) statement;

Flowchart of a while Loop

statement

true

conditionevaluated

false

while ( condition ) statement;

Example

// set initial value of month so that the while condition // below is false initially

int month = -1;

while (month < 1 || month > 12){

System.out.print( “Enter a month (1 to 12): “);

month = scan.nextInt();

}

System.out.print( “Enter a month (1 to 12): “);

int month = scan.nextInt();

while (month < 1 || month > 12){

System.out.println( month + “ is not a valid month.” );

System.out.print( “Enter a month (1 to 12): “);

month = scan.nextInt();

}

The do Statement: Syntax

do{ statement;}while ( condition );

BothBoth dodo and andwhilewhile

arearereservedreserved

wordswords

The The statementstatement is executed once initially, then the is executed once initially, then the conditioncondition is evaluated is evaluated

The The statementstatement is repetitively executed until the is repetitively executed until the conditioncondition becomes false becomes false

Flowchart of a do Loop

truetrue

conditionevaluated

statement

falsefalse

do{ statement;}while ( condition );

Comparing the while and do Loops

statement

truetrue

conditionevaluated

falsefalse

while loopwhile loop

truetrue

conditionevaluated

statement

falsefalse

do loopdo loop

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

Example

int month; // no need to initialize month

do

{

System.out.print( “Enter a month (1 to 12): “);

month = scan.nextInt();

} while (month < 1 || month > 12);

// beginning of the next statement

The for Statement: Syntax

for ( initialization ; condition ; increment ) statement;

ReservedReservedwordword

The The initializationinitialization portion portionis executed onceis executed once

before the loop beginsbefore the loop begins

The statement isThe statement isexecuted until theexecuted until the

conditioncondition becomes false becomes false

The The incrementincrement portion is executed at the end of each iteration portion is executed at the end of each iteration

Both semi-colons are always Both semi-colons are always requiredrequired

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

Flowchart of a for loop

statement

truetrue

conditionevaluated

falsefalse

increment

initialization

for ( initialization ; condition ; increment ) statement;

The for Statement

• A for loop is equivalent to the following while loop structure:

initialization;while ( condition ){ statement; increment;}

for ( initialization ; condition ; increment ) statement;

The for Statement: Example

counter++

Establish initial value of control variable.

Determine if final value of control variable has been reached.

counter <= max sum+= counter

true

false

int counter = 1

Body of loop (this may be multiple statements)

Increment the control variable.

int sum = 0;

for (int counter = 1; counter <= max; counter++)

sum += counter;

// beginning of the next statement

Summary: Loop Statements Syntax

while statement

do statement

for statement

while ( condition ) 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

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

Example: Check if a Number is Prime

// check if a positive integer n is prime

boolean canBeDivided = false;for (int i = 2; i < 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!”);}

Example: Reverse a Number

1 2 543 7 6

number reverse

The state is captured by number and reverse.

1 2 543

number

6 7 7 6 345

reverse

2 1

Example: Reverse a Number

1 2 43 7 6

number reverse

{ lastDigit = number % 10; reverse = reverse * 10 + lastDigit;

}

5 5

number % 10 reverse = reverse * 10 + number % 10

number = number / 10;

reverse = 0;while (number > 0)

int reverse , lastDigit;

int intReverse (int number){

}

Example: Reverse a Number

1 2 43 7 6

number reverse

reverse = 0;while (number > 0){ lastDigit = number % 10; reverse = reverse * 10 + lastDigit; number = number / 10;}

5

Example: Play Games// initialize global state variables// such as statisticsboolean 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

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.

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

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

Methods

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

Method Declaration: Header

• A method declaration begins with a method header

methodmethodnamename

returnreturntypetype

parameter listparameter list

The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter

The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument

class MyClass { static int min ( int num1, int num2 )

propertiesproperties

Method Declaration: Body

The header is followed by the method body:

static int min(int num1, int num2){ int minValue = num1 < num2 ? num1 : num2; return minValue;}

class MyClass{

}

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

Calling a Method• Each time a method is called, the values of the actual

arguments in the invocation are assigned to the formal arguments

static int min (int num1, int num2)

{ int minValue = (num1 < num2 ? num1 : num2); return minValue;}

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

Method Overloading

double tryMe (int x){ return x + .375;}

Version 1Version 1

double tryMe (int x, double y){ return x * y;}

Version 2Version 2

result = tryMe (25, 4.32)

InvocationInvocation

More Examples

double tryMe ( int x ) { return x + 5;}

double tryMe ( double x ) { return x * .375;}

double tryMe (double x, int y){ return x + y;}

tryMe( 1 );

tryMe( 1.0 );

tryMe( 1.0, 2);

tryMe( 1, 2);

tryMe( 1.0, 2.0);

Which tryMe will be called?

Variable Scoping

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

Example of Variable Typespublic 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

Scope of Variables• 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

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;…

} …

}

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

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…

Recommended