3-1 chapter 3 flow of control (part a - branching)

47
3-1 Chapter 3 Flow of Control (part a - branching)

Upload: mackenzie-roche

Post on 28-Mar-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 3-1 Chapter 3 Flow of Control (part a - branching)

3-1

Chapter 3

Flow of Control (part a - branching)

Page 2: 3-1 Chapter 3 Flow of Control (part a - branching)

3-2

Flow of Control in a program

Programstatements

Programstatements

Programstatements

either or (branching)

repetition

(or loop)

Page 3: 3-1 Chapter 3 Flow of Control (part a - branching)

3-3

Flow of Control

• Java has several branching mechanisms for either / or: if, if-else, and switch statements

• Java has three types of loop statements for repeating actions: the while, do-while, and for statements

• Most branching and looping statements are controlled by Boolean expressions

Page 4: 3-1 Chapter 3 Flow of Control (part a - branching)

3-4

The if statement

– General form:if( logical-expression );

true-part executes if logical express is true

– A logical-expression is any expression that evaluates to true or false

– eg

sales < 15000.00

hoursWorked > 40

true || false //|| is the OR operator

Page 5: 3-1 Chapter 3 Flow of Control (part a - branching)

3-5

Java Comparison Operators

Page 6: 3-1 Chapter 3 Flow of Control (part a - branching)

3-6

Basic if statement semantics

• Syntaxif (Expression)

Action

• Semantics If the Expression is true then

execute Action

• Action is either a single statement or a group of statements within braces

Expression

Action

true false

Page 7: 3-1 Chapter 3 Flow of Control (part a - branching)

3-7

Branching with an if-else Statement

• An if-else statement chooses between two alternative statements based on the value of a Boolean expression

if (Boolean_Expression) Yes_Statementelse No_Statement

– The Boolean_Expression must be enclosed in parentheses

– Only if the Boolean_Expression is true is the Yes_Statement executed

– If the Boolean_Expression is false, then the No_Statement is executed

Page 8: 3-1 Chapter 3 Flow of Control (part a - branching)

3-8

Compound Statements

Each Yes_Statement and No_Statement branch of an if-else can be a made up of a single statement or many statements

if (myScore > your Score) { System.out.println("I win!"); wager = wager + 100;}else{ System.out.println ("I wish these were golf scores."); wager = 0;}

Page 9: 3-1 Chapter 3 Flow of Control (part a - branching)

Simple example

• Suppose you have input salary and deductions. Write an if - else statement that outputs the word Crazy if deduction are less than salary; otherwise calculate the net salary as salary less deductions and output the message OK.

 

If (salary < deductions)

{

System.out.println("Crazy");

}

else

{

System.out.println("OK");

net = salary - deductions;

}

 

3-9

Page 10: 3-1 Chapter 3 Flow of Control (part a - branching)

The Ternary Operator ? :

The conditional if:

if (n1 > n2)

max = n1;

else

max = n2;

Can be expressed using the ternary operator:

max = (n1 > n2) ? n1 : n2

This gives an identical action to the usual conditional if.

3-10

Page 11: 3-1 Chapter 3 Flow of Control (part a - branching)

3-11

Boolean Expressions

• The simplest Boolean expressions compare the value of two expressions

time < limityourScore == myScore

– Again note that Java uses two equal signs (==) to perform equality testing: A single equal sign (=) is used only for assignment

Page 12: 3-1 Chapter 3 Flow of Control (part a - branching)

3-12

Multiway if-else Statement

if (Boolean_Expression) Statement_1else if (Boolean_Expression) Statement_2 else if (Boolean_Expression_n) Statement_nelse Statement_For_All_Other_Possibilities

. . .

Page 13: 3-1 Chapter 3 Flow of Control (part a - branching)

Multiway if-else Statement

• Consider the following:

(a < b) ?

(b < c) ?

(a < c) ?

(b < c) ?(c < b < a) ?

(b < c < a) ?

(b < a < c ) ?

(c < a < b) ?

(a < c < b) ?

(a < c) ?

(a < b < c) ?true

true

true

true

true

false

false

false

false

false

Page 14: 3-1 Chapter 3 Flow of Control (part a - branching)

Multiway if-else StatementFirst attempt: The compiler always matches the else to the latest

(previous) unmatched if:

If (a<b)

if (b<c) System.out.println(“a<b<c”);

else

if (a<c) System.out.println(“a<c<b”);

else

if (a<c) System.out.println(“b<a<c”);

else

if (b<c) System.out.println(“b<c<a”);

else System.out.println(“c<b<a”);

Would compile but gives the wrong answer as the c <a < b branch cannot be printed

Page 15: 3-1 Chapter 3 Flow of Control (part a - branching)

Multiway if-else StatementSecond attempt: The compiler always matches the else to the latest

unmatched if:

If (a<b)

if (b<c) System.out.println(“a<b<c”);

else

if (a<c) System.out.println(“a<c<b”);

else System.out.println(“c<a<b”);

else

if (a<c) System.out.println(“b<a<c”);

else

if (b<c) System.out.println(“b<c<a”);

else System.out.println(“c<b<a”);

The correct answer!

Page 16: 3-1 Chapter 3 Flow of Control (part a - branching)

3-16

Defining boolean variables

• Boolean variables are uninitialized when declared

boolean isMyLogic;boolean receivedAcknowledgement;boolean haveFoundMissingLink;

No value stored in memory

-isMyLogic

-receivedAcknowledgement

-haveFoundMissingLink

Page 17: 3-1 Chapter 3 Flow of Control (part a - branching)

3-17

Defining boolean variables

• Boolean variables with initialization

boolean canProceed = true;boolean preferCyan = false;boolean completedSecretMission = true;

Most problems require initialisation

truecanProceed

falsepreferCyan

truecompletedSecretMission

Page 18: 3-1 Chapter 3 Flow of Control (part a - branching)

3-18

Building Boolean Expressions• Reminder from maths:

• When two Boolean expressions are combined using the "and" (&&) operator, the entire expression is true provided both expressions are true– Otherwise the expression is false

• When two Boolean expressions are combined using the "or" (||) operator, the entire expression is true as long as one of the expressions is true– The expression is false only if both expressions are false

• Any Boolean expression can be negated using the ! operator– Place the expression in parentheses and place the ! operator in front of it

• Unlike mathematical notation, strings of inequalities must be joined by &&– Use (min < result) && (result < max) rather than min < result <

max

Page 19: 3-1 Chapter 3 Flow of Control (part a - branching)

3-19

Evaluating Boolean Expressions

• A Boolean expression can be evaluated in the same way that an arithmetic expression is evaluated

• The only difference is that arithmetic expressions produce a number as a result, while Boolean expressions produce either true or false as their result

boolean madeIt = (time < limit) && (limit < max);

Page 20: 3-1 Chapter 3 Flow of Control (part a - branching)

3-20

Short-Circuit and Complete Evaluation• Java can take a shortcut when the evaluation of the first

part of a Boolean expression produces a result that evaluation of the second part cannot change

• This is called short-circuit evaluation or lazy evaluation– For example,

if (boolean is false) or …………….. short-circuit

if (boolean is true) || …………….. short-circuit

Page 21: 3-1 Chapter 3 Flow of Control (part a - branching)

3-21

Evaluating Expressions

• Parentheses: In general, parentheses in an expression help to document the programmer's intent

– Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious

• Binding: The association of operands with their operators

– A fully parenthesized expression accomplishes binding in am easy an obvious way

Page 22: 3-1 Chapter 3 Flow of Control (part a - branching)

3-22

Note on equivalence• Using equivalence to test object references and primitive objects, such as

integers, is without ambiguity providing that the primitive object is not a floating point number.

• Floating point numbers must be handled with care as their representation is not exact.

Given double x,y; where x=1.5; y=2.25/x; (thus x and y are 1.5)what does the following return?

if( x == y ) System.out.print( “same” );else System.out.print( “different” );

Answer: different (almost certainly)

Page 23: 3-1 Chapter 3 Flow of Control (part a - branching)

3-23

Note on equivalence

• Given double x,y; x=1.5; y=2.25/x;what does the following return?

if ( Math.abs( x - y ) <= epsilon ) System.out.print( “same” );else System.out.print( “different” );

Where epsilon is chosen small, say 1e-7 for a double variable, (1e-4 for a float variable).

Now the return value is same.

Page 24: 3-1 Chapter 3 Flow of Control (part a - branching)

3-24

The switch Statement• The switch statement is the only other kind of Java

statement that implements multiway branching

– When a switch statement is evaluated, one of a number of different branches is executed

– The choice of which branch to execute is determined by a controlling expression enclosed in parentheses after the keyword switch

• The controlling expression must evaluate to a char, int, short, or byte. We will use char or int

Page 25: 3-1 Chapter 3 Flow of Control (part a - branching)

3-25

The switch Statement

switch (Controlling_Expression){ case Case_Label_1: Statement_Sequence_1 break; case Case_Label_2: Statement_Sequence_2 break; case Case_Label_n: Statement_Sequence_n break; default: Default_Statement Sequence break;}

. . .

Page 26: 3-1 Chapter 3 Flow of Control (part a - branching)

3-26

The switch Statement• Note, each branch statement in a switch statement

starts with the reserved word case, followed by a constant called a case label, then a sequence of statements

– Each case label must be of the same type as the controlling expression

– Case labels need not be listed in order or span a complete interval, but each one may appear only once

– Each sequence of statements may be followed by a break statement ( break;)

Page 27: 3-1 Chapter 3 Flow of Control (part a - branching)

3-27

The switch Statement• Note

– When the computer executes the statements after a case label, it continues until a break statement is reached

– If the break statement is omitted, then after executing the code for one case, the computer will go on to execute the code for the next case

– If the break statement is omitted inadvertently, the compiler will not issue an error message

• There can also be a section labeled default:– The default section is optional, and is usually last– Even if the case labels cover all possible outcomes in a given

switch statement, it is still a good practice to include a default section• It can be used to output an error message, for example

Page 28: 3-1 Chapter 3 Flow of Control (part a - branching)

3-28

Chapter 3

Flow of Control (part b - loops)

Page 29: 3-1 Chapter 3 Flow of Control (part a - branching)

3-29

Loops• Loops in Java are used to repeat the action of

a section of code.

• Java has three types of loop statements: the:while,

do-while, for.

– The code that is repeated in a loop is called the body of the loop

– Each repetition of the loop body is called an iteration of the loop

Page 30: 3-1 Chapter 3 Flow of Control (part a - branching)

3-30

while (Boolean_Expression) Statement

Or more generalywhile (Boolean_Expression){ Statement_1 Statement_2

Statement_Last}

– The Boolean expression is checked before the loop body is executed• When false, the loop body is not executed at all

– For each following iteration, the Boolean expression is checked again

while Syntax

. . .

Page 31: 3-1 Chapter 3 Flow of Control (part a - branching)

While Semantics

Expression

Action

true false

Expression isevaluated at the

start of eachiteration of the

loop

If Expression istrue, Action is

executed If Expression isfalse, program

executioncontinues with

next statement

Page 32: 3-1 Chapter 3 Flow of Control (part a - branching)

3-32

While loops - Newton Iteration • Find the root of the equation sin x - 0.5 = 0 using Newton’s method

• xn =xn-1 - f(xn)/f /

(xn)

• Therefore, xn+1 = xn - (sin (xn) - 0.5)/cos(xn)

• Code fragment to solve this equation:

•• x = 0.5; // Initial estimate of root, • notconv = true;• while (notconv)• {• xn = x - (Math.sin(x) - 0.5)/Math.cos(x);• If ( Math.abs(xn - x) < 1e-8)• notconv = false;• else• x = xn; Why?• }• This example could run for ever if the iteration does not converge.

Why?

Page 33: 3-1 Chapter 3 Flow of Control (part a - branching)

3-33

Loop Bugs• The two most common kinds of loop errors are unintended infinite

loops and off-by-one errors

– An off-by-one error is when a loop repeats the loop body one too many or one too few times

• This usually results from a carelessly designed Boolean test expression

• If the Boolean expression remains true, then the loop will run forever, resulting in an infinite loop

– Use of == or != in the controlling Boolean expression can lead to an infinite loop or an off-by-one error

• This sort of testing works only for characters and integers, and should never be used for floating-point

Page 34: 3-1 Chapter 3 Flow of Control (part a - branching)

3-34

Tracing Variables in loops, etc• Tracing variables involves watching one or more

variables change value while a program is running

• This can make it easier to discover errors in a program and debug them

• Many IDEs (Integrated Development Environments) have a built-in utility that allows variables to be traced without making any changes to the program

• Another way to trace variables is to simply insert temporary output statements in a programSystem.out.println("n = " + n); // Tracing n

– When the error is found and corrected, the trace statements can simply be commented out. The marker can then see your good practice for testing the integrity of your design.

Page 35: 3-1 Chapter 3 Flow of Control (part a - branching)

• Case Studies on Newton iteration

with while-loop

Protect against unlimited iterations

3-35

Page 36: 3-1 Chapter 3 Flow of Control (part a - branching)

3-36

do-while Statement• Similar to the while statement but the logical test is at the end of the loop

– The loop body is executed at least once• The Boolean expression is checked after the loop body is executed

– The Boolean expression is checked after each iteration of the loop body

• If true, the loop body is executed again• If false, the loop statement ends• Don't forget to put a semicolon after the Boolean expression

– Like the while statement, the loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ })

Page 37: 3-1 Chapter 3 Flow of Control (part a - branching)

The do-while statementSemantics of do-while

– Execute Action once

– If Expression is true then execute Action again

– Repeat this process until Expression evaluates to false

• Syntax of do-whiledo Statementwhile (Boolean_Expression);

Or more generallydo { Statement_1 Statement_2

Statement_Last} while (Boolean_Expression);

Action

true

false

Expression

Semantics

Page 38: 3-1 Chapter 3 Flow of Control (part a - branching)

3-38

Sentinel Loops – to control size of loop

– A sentinel is a specific input from the user to signal that there is no more data to be input. We use this method to enable us to vary the length of the input stream of data, without having to count the number of data items

• The sentinel should be the same type of data as being processed in the loop.• The sentinel must not be in the valid range of data.

• Example: Enter exam scores or -1 to indicate that we have reached the end of the input data stream.

• 80 95 76 82 56 100 45 86 -1

-1 is the sentinel.As exam scores are between 1 and 100, the sentinel is out of the range of valid data.

Page 39: 3-1 Chapter 3 Flow of Control (part a - branching)

3-39

Summation construct• This is a useful programming construct for the summation of a set of numbers:

• Sum 1, 2, 3, 5, 2, 7, 9, 10.

• Set sum initially to 0, sum = 0;

• Traverse the list adding in each term using• sum = sum + nextTerm; Then

• sum = sum + nextTerm; sum is 0 + 1 giving 1• sum = sum + nextTerm; sum is 1 + 2 giving 3• sum = sum + nextTerm; sum is 3 + 3 giving 6• . . sum = sum + nextTerm; sum is 29 + 10 giving

39

• A for loop is one obvious way of controlling this construct.

Page 40: 3-1 Chapter 3 Flow of Control (part a - branching)

3-40

The for Statementfor (Initializing; Boolean_Expression; Update) {code to be repeated}

Usually, the total number of repeats are known.

– The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration

– The second expression determines when the loop should end, based on the evaluation of a Boolean expression before each iteration

– The third expression tells how the control variable or variables are updated after each iteration of the loop body

Page 41: 3-1 Chapter 3 Flow of Control (part a - branching)

3-41

The for Statement Syntaxfor (Initializing; Boolean_Expression; Update) {code to be repeated}

• The Body may consist of a single statement or a list of statements enclosed in a pair of brackets ({ })

• Note that the three control expressions are separated by two semicolons

• Note that there is no semicolon after the closing parenthesis at the beginning of the loop

Page 42: 3-1 Chapter 3 Flow of Control (part a - branching)

3-42

Semantics of the for Statement

Page 43: 3-1 Chapter 3 Flow of Control (part a - branching)

3-43

The Comma in for Statements• A for loop can contain multiple initialization actions separated

with commas

eg

imax=6;

jmin =6;

for(i=1, j=10; (i<imax) && (j>jmin); i=i+1,j=j-1)

{code to be repeated}

• A for loop can contain multiple update actions, separated with commas

• However, a for loop can contain only one Boolean expression to test for ending the loop

Page 44: 3-1 Chapter 3 Flow of Control (part a - branching)

3-44

Example for-loop to produces an average

public class summation { public static void main(String[ ] args) { int sum, n, nextTerm; double average; Scanner keyboard = new Scanner(System.in);

System.out.print( “ How many numbers do you wish to average? "); n = keyboard.nextInt( );

for( int j = 1; j <= n; j = j + 1 ) // Repeat n times { System.out.print("Enter number: "); nextTerm = stdin.nextInt( ); sum = sum + nextTerm;

} average = sum / (double) n; System.out.print( "Average of " + n + " numbers is " + average )}

Page 45: 3-1 Chapter 3 Flow of Control (part a - branching)

3-45

Incremental Assignment Operators

We have three methods for the incrementing the for-loop. These methods have identical action:

for( int j = 1; j <= n; j = j +1 ),

for( int j = 1; j <= n; j ++ ),

for( int j = 1; j <= n; j +=1 ),

each having the same result of incrementing j by 1 for each pass through the loop.

Page 46: 3-1 Chapter 3 Flow of Control (part a - branching)

3-46

Nested Loops

• Loops can be nested, just like other Java structures– When nested, the inner loop iterates from beginning to end for each

single iteration of the outer loop

int rowNum, columnNum;for (rowNum = 1; rowNum <=3; rowNum++)

for (columnNum = 1; columnNum <=2; columnNum++) {System.out.print(" row " + rowNum + " column " + columnNum); System.out.println();

}

Page 47: 3-1 Chapter 3 Flow of Control (part a - branching)

3-47

The exit Statement• A break statement will end a loop or switch

statement, but will not end the program

• The exit statement will immediately end the program as soon as it is invoked:System.exit(0);

• The exit statement takes one integer argument

– By tradition, a zero argument is used to indicate a normal ending of the program