Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining."— Presentation transcript:

1 Control Structures

2 2  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

3 3  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.

4 4  The single-branch (one way) if statement is the simplest selection. if( some_condition ) { then_clause } 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

5 5 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.

6 6  The if-else statement is a two-way conditional. if( some_condition ) { then_clause } else { else_clause } 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

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

8 8 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.

9 9  The if statement can be ‘multi-way’ if( condition1 ) { clause1 } else if( condition2 ) { clause2 } else if( condition3) { clause3 } else { default } if( condition1 ) { clause1 } else if( condition2 ) { clause2 } else if( condition3) { clause3 } else { default }

10 10 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

11 11  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.

12 12  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.

13 13  While loop  Best used to solve indefinite looping problems while( condition ) { loopBody } while( condition ) { loopBody }

14 14 int sum, count; sum = 0; count = 1; while (count < 6 ) { sum = sum + count; count++; } System.out.println(sum);

15 15  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);

16 16  Original: sum == 1+2+3+4+5  What 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);

17 17  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?

18 18 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; }

19 DayperDaySueperDaySamtotalSuetotalSam 11100001 2220000330000 34 760000 484000015100000 5165000031150000 6326000063210000 76470000127280000 812880000255360000 925690000511450000 105121000001023550000 1110241100002047660000 1220481200004095780000 1340961300008191910000 148192140000163831050000 1516384150000327671200000 1632768160000655351360000 17655361700001310711530000 181310721800002621431710000 192621441900005242871900000 2052428820000010485752100000 21104857621000020971512310000 22209715222000041943032530000 23419430423000083886072760000 248388608240000167772153000000 2516777216250000335544313250000 2633554432260000671088633510000 27671088642700001342177273780000 281342177282800002684354554060000

20 20  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--; } int n = Keyboard.readInt(); int result = 1; while( n > 0) { result = result * n; n--; }

21 21  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--; } double x = Keyboard.readDouble(); int y = Keyboard.readInt(); double result = 1; while( y > 0) { result = result * x; y--; }

22 22  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(); 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); } int x = Keyboard.readInt(); while( x > 0) { x = Math.round( x/ 2.0); }

23 23  Infinite loops are not always ‘bad’! int n = Keyboard.readInt(); int result = 1; while(n != 0) { result = result * n; n--; } 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--; } int n = Keyboard.readInt(); int result = 1; while(n > 0) { result = result * n; n--; } Which is more logically correct?

24 24 int k = 1; while( k != 100 ) { // main work k++; } int k = 1; while( k != 100 ) { // main work k++; } int k = 100; while( k >= 0 ) { // main work k--; } int k = 100; while( k >= 0 ) { // main work k--; } int k = 0; while( k < 99 ) { // main work k++; } int k = 0; while( k < 99 ) { // main work k++; } int k = 1; while( k < 100 ) { // 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--; } int k = 99; while( k > 0 ) { // main work k--; }

25 25  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++; } 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++; }

26 26  A repetition statement that executes the body 1 or more times. do { loopBody } while( condition );

27 27  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( ?? ); int minValue = 10, maxValue = 100; int result; do { result = Keyboard.readInt(); } while( ?? );

28 28  Best used for ‘definite’ looping  Typically uses a counter for( init ; condition ; make_progress) { main_work }

29 29  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); }

30 30  Print all odd numbers between 1 and 100 for( int n=1; n <= 100; n+=2) { System.out.println(n); }

31 31  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 1 2 4 8 16 32 3 9 27 81 243 4 16 63 256 1024 5 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(); }

32 32  A specialized conditional  Use when there are many cases  Can be more efficient switch( expression ) { case CONSTANT1: statements1; break; case CONSTANT2: statements2; break; … case CONSTANTN: statements3; break; default: statementsDefault; }

33 33  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”); }


Download ppt "Control Structures. 2  Control – the order in which instructions are performed in a program.  Control structures are well defined ways of determining."

Similar presentations


Ads by Google