1 / 34

Control Structures

Control Structures. 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. Selection : One way Conditional. Sometimes need to make a choice

Download Presentation

Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Control Structures

  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

  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.

  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

  5. Example PROBLEM: Write a code fragment that determines a pay amount given an hourly wage and the hours worked in a week. Time and a half is given for work over 40 hours during a week. double pay, wage, hours, bonus; // assume that wage, hours, and bonus // values have been initialized

  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

  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

  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.

  9. Conditionals : Multiway • The if statement can be ‘multi-way’ • if( condition1 ) { • clause1 • } else if( condition2 ) { • clause2 • } else if( condition3) { • clause3 • } else { • default • }

  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

  11. Sample program • A certain bank offers 10, 20 and 30 year fixed rate mortgages. The interest rate is 8% for a 10 year loan, 7% for 20 and 6% for 30. • Write a program to read the number of years of the mortgage and the mortgage amount. Compute the monthly payment amount. • M = P * R / (1 – (1 + R)^(-N)) • P = Principal • R = Periodic interest rate • N = Number of payment periods • M = periodic payment

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

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

  14. Repetition: While • While loop • Best used to solve indefinite looping problems while( condition ) { loopBody }

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

  16. 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);

  17. Tweaking the parts • 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);

  18. 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?

  19. 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; }

  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(); intresult = 1; while( n > 0) { result = result * n; n--; }

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

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

  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?

  24. Off by one Which of these executes the main work 100 times? int k = 1; while( k != 100 ) { // main work k++; } int k = 100; while( k >= 0 ) { // main work k--; } int k = 1; while( k < 100 ) { // main work k++; } int k = 99; while( k > 0 ) { // main work k--; } int k = 0; while( k < 99 ) { // main work k++; }

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

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

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

  28. For Loop • Best used for ‘definite’ looping • Typically uses a counter for( init ; condition ; make_progress) { main_work }

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

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

  31. Nested For Loops 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 • 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. 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. Switch statement(cleaning up with conditionals) • 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. 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”); }

More Related