1 / 48

Control Structures

Control Structures. Corresponds with Chapters 3 and 4. Control Statements. Decisions (selections) if statements switch statements Iterations (repetitions) for loops (enumerated) while loops (top-tested) do while loops (bottom-tested). Must be enclosed in parentheses.

jerrod
Télécharger la présentation

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 Corresponds with Chapters 3 and 4

  2. Control Statements • Decisions (selections) • if statements • switch statements • Iterations (repetitions) • for loops (enumerated) • while loops (top-tested) • do while loops (bottom-tested)

  3. Must be enclosed in parentheses. Evaluates to true or false if Statement if (booleanExpression) single statement; Remember to indent the subordinate statement

  4. If you have multiple subordinate statements, these must be a block enclosed in braces. if Statement if (booleanExpression) { statement1; statement2; … statementn; }

  5. false Boolean test true Subordinate statement(s) Independent statement(s) if flowchart

  6. boolean value boolean value boolean value Statement executes only if both conditions are true Example: if (i >= 0 && i <= 10) System.out.println("i is an integer between 0 and 10");

  7. The if...else Statement if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } Note: blocks with braces are necessary when there are multiple subordinate statements. They are optional when there is a single subordinate statement.

  8. false Boolean test true statement(s) subordinate to if statement(s) subordinate to else Independent statement(s) if-- else flowchart

  9. if...else Example The if branch statement must be in a block because there are two of them. if (radius >= 0) { area = radius*radius*PI; System.out.println("The area for the " + "circle of radius " + radius + " is" + area); } else System.out.println("Negative input"); There is only one else-branch statement. It does not need to be in a block, but you can if you want.

  10. This is true indentation for the nesting… inner ifs are nested within else of previous if statement. This has the same effect, but is more readable. Unlike VB, there is no ElseIf clause in Java, but the else if lines make it look like a VB ElseIf. Similar idea to figure 3.3 p76 Nested if Statements

  11. false false Boolean test Boolean test true true statement(s) subordinate to elseif statement(s) subordinate to if statement(s) subordinate to else Independent statement(s) FlowChart for if – else if -- else

  12. Nesting an if - else inside the if portion if (boolean expression1) if (boolean expression2) statement1; else statement2; The nested if-else. NOTE: an else is always associated with the most recent if. This else is the result of boolean expression2, not boolean expression1.

  13. true false Boolean test1 Boolean test2 false true statement1 subordinate to success on boolean test2. Therefore both tests succeeded. statement2 subordinate to success on boolean test2. Therefore test1 succeeded and test2 failed. Independent statement(s) FlowChart for if with nested if -- else

  14. Outer if-else with a nested if (no inner else) if (boolean expression1){ if (boolean expression2) statement1; } else statement2; The nested if. NOTE: here, because of the braces, the else is associated with the if for boolean expression #1.

  15. false true Boolean test1 Boolean test2 false true statement1 subordinate to success on boolean test2. Therefore both tests succeeded. statement2 subordinate to failure of boolean test1 (the outer else). Independent statement(s) FlowChart for if -elsewith nested if

  16. test Shortcut if Statements if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; if else Returned if true Returned if false

  17. switch-expression can evaluate to char, byte, short, or int. break causes control to skip past the end of the switch block. Without break, control would fall through to the next case. switch Statements switch (switch-expression) { case value1: statement(s) 1; break; case value2: statement(s) 2; break; … case valueN: interestRate = 9.0; statement(s) N; break; default: statement(s) for default; } No break needed for last condition

  18. switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0); }

  19. switch Statement Flow Chart

  20. Equivalent if statement if (status == 0) compute tax for single filers; else if (status == 1) compute tax for married filing jointly; else if (status == 2) compute tax for married filing separately; else if (status == 3) compute tax for head of household; else{ System.out.println( ("Errors: invalid status"); System.exit(0); }

  21. Exercise if (a==1) x += 6; else if (a == 2) x += 10; else if (a == 3) x += 16; else if (a == 4) x += 34; Convert this if statement into a switch statement

  22. while Loops while (continue-condition) { // loop-body; } Top-tested loop Test before performing statements of loop Loop body may never execute

  23. Listing 4.4 p109 – User Decides when to quit Initial data input – before the loop Subsequent data inputs – toward the end of the loop body

  24. Do-while Loops do { //loop body; } while (continue-condition) Bottom-tested loop Perform statements of loop before testing Always enter the loop body at least once

  25. Listing 4.5 – a Do-While Loop Test is at the bottom

  26. for Loops 1) assignment statement for (control variable initialization; continue-test; adjustment-statement) { //loop body; } 2) boolean expression 3) assignment statement • Set initial value for loop counter (only once, before looping starts) • Test loop counter (also called control variable) to see if it is less than the max loop allowed (before executing loop body) • Increment loop counter (after executing loop body) (usually an increment operator).

  27. for Loop Flow Chart

  28. for Loop Example: int i; for (i = 0; i<100; i++) { System.out.println(“Hi. i is:” + i); } Here, the loop counter variable (calledi) is available for use outside the loop.

  29. Alternative Syntax:Declare Loop Counter in Initialization for (int i = 0; i<100; i++) { System.out.println(“Hi. i is:” + i); } Here, the loop counter variable (calledi) is available for use only within the loop.

  30. Body of outer loop Body of inner loop The Nested for Loop for (int i=0; i<outerLoopLimit;i++){ outer loop statement(s); for (int j=0;j<innerLoopLimit;j++){ inner loop statement(s); } outer loop statement(s); } Body of outer loop will execute outerLoopLimit times Body of inner loop will execute innerLoopLimit times for each time the outer loop body executes.  Total innerLoopLimit * outerLoopLimit times!

  31. Initialize outer loop counter Initialize inner loop counter Outer loop statement(s) Outer loop statement(s) Inner loop statement(s) Increment outer loop counter Increment inner loop counter Test to continue outer loop Test to continue inner loop The Nested for Loop -- Flowchart Statements preceding loop No Statements following loop Yes No Yes

  32. Inner loop Outer loop Nested Loop Example(my example)

  33. Example Program Run

  34. Max loop count value can be any numeric expression. Here it’s a variable Special escape character \t for tab. A couple points about the example

  35. Reminders about packages from the example The classNestedForLoop is in the package called controlStructurePackage. Therefore, there is a file called NestedForLoop.class in a folder called controlStructurePackage.

  36. Reminders about packages from the example In order to use a class from outside your own package, you must import the package that the class is contained in. Here, we import the JOptionPane class from the javax.swing package.

  37. Another Example -- listing 4.6 p115

  38. Loop with single statement in body Listing 4.6

  39. Listing 4.6 An if statement nested inside a for loop, which is itself nested in another for loop.

  40. Listing 4.6 Note: actions in the loops are concatenating values into the string output. At the end, the string is displayed in the output screen

  41. Listing 4.6 program analysis Question 1: how many times will outer loop body execute? Question 2: how many times will inner loop body execute? Question 3: how many times will IF branch execute?

  42. The break Keyword break can be used to terminate the loop based on decisions inside the loop body.

  43. Listing 4.11 Using the break keyword Question: how many times will this loop body execute? What will be the value in sum?

  44. The continue Keyword continue can be used to branch to the top of the loop (skipping statements in loop body) based on decisions inside the loop body.

  45. Listing 4.12Using the continue keyword Question 1: how many times will this loop body execute? Question 2: how many times sum += number; execute?

  46. Statements following loop Yes Present menu options to user Input User Choice Choice 1 statement(s) Choice n statement(s) No User wants to quit? User choice 1? User choice n? Yes No Yes No Typical Nested Structure: Decision within a Loop(menu-driven as first statement in loop)

  47. A Java Implementation This implementation nests a switch inside a while loop. Exercise: Do the same thing by nesting an if statement inside a do-while loop.

  48. Other Useful Examples • Listing 4.8: finding the greatest common divisor (while loop with nested if statement) • Listing 4.9: finding a sales amount (do-while loop with nested if - else if - else statement) • Listing 4.10: printing a pyramid (outer for loop with three nested for loops inside it) • Listing 4.14: finding prime numbers (outer while loop with nested for loop with nested if statement)

More Related