control structures. 2 control – the order in which instructions are performed in a program. ...

33
Control Structures

Upload: sara-curtis

Post on 03-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

Control Structures

Page 2: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

2

Control

Control – the order in which instructions are performed in a program.

Control structures are well defined ways of determining instruction flow.

Two main types Selection Repetition

Others later

Page 3: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

3

Selection : One way Conditional

Sometimes need to make a choice If the amount of an Amazon.com

purchase is less than 25 then add shipping

If a bank withdrawal would yield a negative balance then don’t allow the withdrawal

If a user enters a SSN that is not consist of exactly 9 digits then print an error message.

Page 4: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

4

Selection : One way Conditional

The single-branch (one way) if statement is the simplest selection.

if( some_condition ) {then_clause

}

some_condition: Any expression that has boolean type

then_clause: A statement sequence the ‘{}’ is not needed if the then clause is a

single statement but should be used

Page 5: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

5

Example

PROBLEM: Write a code fragment that prints the message "Overtime" if an employee has worked more than 40 hours in the past week..

double hoursWorked;// assume that hoursWorked // has been initialized.

Page 6: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

6

Conditional : Two-way

The if-else statement is a two-way conditional.if( some_condition ) {

then_clause} else { else_clause}

some_condition: Any expression that has boolean type

then_clause: A statement sequence else_clause: A statement sequence

Page 7: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

7

Conditional Example

PROBLEM: Write a code fragment that determines the total cost of an internet purchase. The company charges a flat fee of $5 shipping if the purchase amount is less than $30 otherwise they charge $5 plus 5% of the purchase for shipping. All values are in pennies.

int totalCost, purchaseAmount;//assume purchaseAmount is initialized

Page 8: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

8

Conditional Examples

PROBLEM: Write a code fragment that takes two ints (variables ‘a’ and ‘b’) and computes the largest of the two values as variable ‘max’.

PROBLEM: Write a code fragment that takes three ints and computes the largest of the three values.

Page 9: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

9

Conditionals : Multiway

The if statement can be ‘multi-way’

if( condition1 ) {clause1

} else if( condition2 ) { clause2} else if( condition3) { clause3} else { default}

Page 10: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

10

Conditionals : Example

PROBLEM: Write a code fragment that determines the final cost for an internet purchase. If the purchase amount exceeds $100 the discount is 15%. If the amount is more than $75 up to $100 the discount is 10% else if the amount is more than $50 up to $75 the discount is 5% else the discount is 2.5%.

int finalCost, purchaseAmount;//assume purchaseAmount is initialized

Page 11: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

11

Repetition

Sometime need to execute a code fragment more than once.

Loops can be classified as either ‘definite’ or ‘indefinite’ Definite – the number of repetitions is

known by the programmer immediately prior to execution of the loop.

Indefinite – the number of repetitions is not known by the programmer.

Page 12: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

12

Examples

Assume the following problems are to be solved with loops. Identify as either definite or indefinite. Print the first ten letters of the alphabet. Print the alphabet up to and including the letter

“R” Calculate the first integer power of 83 that is

greater than one billion Starting with distance d1 and d2 repeatedly

divide them both in half until the resulting lengths are within 1 inch of each other.

Page 13: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

13

Repetition: While

While loop Best used to solve indefinite looping

problems

while( condition ) {loopBody

}

Page 14: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

14

While loop example

int sum, count;

sum = 0;count = 1;while (count < 6 ) {

sum = sum + count;count++;

}

System.out.println(sum);

Page 15: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

15

Parts to a loop

Every loop has four parts Initialization – establish the state prior to

entering the loop Primary work – the code that is to be repeatedly

executed Condition – a boolean criteria that controls when

the loop stops Make progress – code that moves the loop

toward termination.

int sum, count;sum = 0;count = 1;while (count < 6 ) {

sum = sum + count;count++;

}System.out.println(sum);

Page 16: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

16

Tweaking the parts

Original: sum == 1+2+3+4+5What changes are needed to cause

the following postconditions? sum == 1+2+3+…+25 sum == 3+4+5+…+25 sum == 1+3+5+…+11

int sum, count;sum = 0;count = 1;while (count < 6 ) {

sum = sum + count;count++;

}System.out.println(sum);

Page 17: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

17

Examples

Write code to print the circumference and area of circles with radius of 10, 20, …, 100.

Sam earns $100 per day with a daily raise of $100. Sue earns $0.01 per day with a salary that doubles every day. How many days pass before Sue’s total income exceeds Sam’s?

Page 18: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

18

Sample Solution

totalSam = 0;totalSue = 0;perDaySam = 10000;perDaySue = 1; dayCount = 0;while ( totalSue <= totalSam ) {

dayCount++;totalSam = totalSam + perDaySam;totalSue = totalSue + perDaySue;perDaySam = perDaySam + 10000;perDaySue = perDaySue * 2;

}

Page 19: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

Day perDaySue perDaySam totalSue totalSam

1 1 10000 1 10000

2 2 20000 3 30000

3 4 30000 7 60000

4 8 40000 15 100000

5 16 50000 31 150000

6 32 60000 63 210000

7 64 70000 127 280000

8 128 80000 255 360000

9 256 90000 511 450000

10 512 100000 1023 550000

11 1024 110000 2047 660000

12 2048 120000 4095 780000

13 4096 130000 8191 910000

14 8192 140000 16383 1050000

15 16384 150000 32767 1200000

16 32768 160000 65535 1360000

17 65536 170000 131071 1530000

18 131072 180000 262143 1710000

19 262144 190000 524287 1900000

20 524288 200000 1048575 2100000

21 1048576 210000 2097151 2310000

22 2097152 220000 4194303 2530000

23 4194304 230000 8388607 2760000

24 8388608 240000 16777215 3000000

25 16777216 250000 33554431 3250000

26 33554432 260000 67108863 3510000

27 67108864 270000 134217727 3780000

28 134217728 280000 268435455 4060000

Salary

0

1000000

2000000

3000000

4000000

5000000

6000000

7000000

8000000

9000000

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Days

Nu

mb

er o

f C

ents

Ear

ned

Sues Salary Sams Salary

Page 20: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

20

Example

Write a code fragment to compute N!Factorial definition

N! = 1*2*3*…*N By convention we define 0! = 1 N must be non-negative

int n = Keyboard.readInt();int result = 1;while( n > 0) { result = result * n; n--;}

Page 21: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

21

Example

Write a code fragment to compute X raised to the Y power. X can be any real value Y must be a non-negative integer

double x = Keyboard.readDouble();int y = Keyboard.readInt();

double result = 1;while( y > 0) { result = result * x; y--;}

Page 22: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

22

Infinite Loop

An infinite loop occurs when termination is never reached. The loop never ends!int x = Keyboard.readInt();

int sum = 0;while( x != 0) { sum = sum + x; x = x - 2;}

int x = Keyboard.readInt();

while( x > 0) { x = Math.round( x/ 2.0);}

Page 23: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

23

Infinite Loops

Infinite loops are not always ‘bad’!int n = Keyboard.readInt();int result = 1;

while(n != 0) { result = result * n; n--;}

Computes n! but what about the logic of n=-1?

int n = Keyboard.readInt();int result = 1;

while(n > 0) { result = result * n; n--;}

Which is more logically correct?

Page 24: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

24

Off by one

int k = 1;while( k != 100 ) { // main work k++;}

int k = 100;while( k >= 0 ) { // main work k--;}

int k = 0;while( k < 99 ) { // main work k++;}

int k = 1;while( k < 100 ) { // main work k++;}

Which of these executes the main work 100 times?

int k = 99;while( k > 0 ) { // main work k--;}

Page 25: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

25

Nested Loops

Premise: A loop is a Java statement Premise: The body of a loop contains a sequence

of Java statements Conclusion: The body of a loop may contain a

loop.int x = 1;while(x < 4) { int y = 1; while(y < 5) { System.out.print(x*y); System.out.print(“ “); y++; } System.out.println(); x++;}

Page 26: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

26

Do Loop

A repetition statement that executes the body 1 or more times.

do {loopBody

} while( condition );

Page 27: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

27

Do Loop Example

Write a code fragment that reads input from the keyboard asking the user repeatedly for input until the input is valid.int minValue = 10, maxValue = 100;int result;

do { result = Keyboard.readInt();} while( ?? );

Page 28: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

28

For Loop

Best used for ‘definite’ looping Typically uses a counter

for( init ; condition ; make_progress) { main_work}

Page 29: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

29

For Loop Example

Print all whole numbers between 5 and 10

for( int n=1; n <= 5; n++) { System.out.println(n + 4);}

for( int n=0; n < 5; n++) { System.out.println(n + 5);}

for( int n=5; n <= 10; n++) { System.out.println(n);}

Page 30: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

30

For Loop Example

Print all odd numbers between 1 and 100

for( int n=1; n <= 100; n+=2) { System.out.println(n);}

Page 31: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

31

Nested For Loops

Write code to print the first 5 powers of each integer value between 1 and N where N is a positive integer read from the keyboard. Print each values power on a single line.

1 1 1 1 12 4 8 16 323 9 27 81 2434 16 63 256 10245 25 125 625 3125

int n = Keyboard.readInt();for(int base=1; base<=n; base++) {

for(int exp=1; exp<=5; exp++) { System.out.print(((int)Math.pow(base,exp)) +

“ “);}System.out.println();

}

Page 32: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

32

Switch statement(cleaning up with conditionals)

A specialized conditionalUse when there are many

casesCan be more efficientswitch( expression ) { case CONSTANT1: statements1; break; case CONSTANT2: statements2; break; … case CONSTANTN: statements3; break; default: statementsDefault;}

Page 33: Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining

33

Switch example

Write a code fragment to determine the interest rate for a mortgage. The bank allows customers to take 3, 5, 7, 20, and 30 year mortgages with annual interest rates of 9%, 8.3%, 7.8%, 7.4% and 6.2% respectively.

double interestRate;System.out.print(“Enter the number of years (3,5,7,20,30): “);int years = Keyboard.readInt();switch( years ) { case 3: interestRate = .09; break; case 5: interestRate = .083; break; case 7: interestRate = .078; break; case 20: interestRate = .074; break; case 30: interestRate = .062; break; default: System.out.println(“invalid year selection”);}