control structures corresponds with chapters 3 and 4
TRANSCRIPT
![Page 1: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/1.jpg)
Control StructuresControl Structures
Corresponds with Chapters 3 and 4Corresponds with Chapters 3 and 4
![Page 2: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/2.jpg)
Control StatementsControl Statements Decisions (selections)Decisions (selections)
ifif statements statements
switchswitch statements statements
Iterations (repetitions)Iterations (repetitions) forfor loops (enumerated) loops (enumerated)
whilewhile loops (top-tested) loops (top-tested)
do whiledo while loops (bottom- loops (bottom-tested)tested)
![Page 3: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/3.jpg)
ifif Statement Statement
if (if (booleanExpressionbooleanExpression) ) single statement;single statement;
Evaluates to true or false
Must be enclosed in parentheses.
Remember to indent the subordinate statement
![Page 4: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/4.jpg)
ifif Statement Statement
if (booleanExpression) { statement1;statement2;…statementn;
}
If you have multiple subordinate statements, these must be a block enclosed in braces.
![Page 5: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/5.jpg)
if flowchartif flowchart
Boolean test
Subordinate statement(s)
Independent statement(s)
true
false
![Page 6: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/6.jpg)
Example:Example:
if (i >= 0 && i <= 10) if (i >= 0 && i <= 10) System.out.println("i is anSystem.out.println("i is an integer between 0 and 10");integer between 0 and 10");
boolean valueboolean value
boolean value
Statement executes only if both conditions are true
![Page 7: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/7.jpg)
The The if...elseif...else Statement Statementif (booleanExpression) if (booleanExpression)
{ {
statement(s)-for-the-true-case;statement(s)-for-the-true-case;
}}
else else
{{
statement(s)-for-the-false-case;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.
![Page 8: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/8.jpg)
if-- else flowchartif-- else flowchart
Boolean test
statement(s) subordinate to if
Independent statement(s)
true
false
statement(s) subordinate to else
![Page 9: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/9.jpg)
if...elseif...else Example Example
if (radius >= 0)if (radius >= 0){ { area = radius*radius*PI;area = radius*radius*PI; System.out.println("The area for the " System.out.println("The area for the " + "circle of radius " + radius + " is" + "circle of radius " + radius + " is"
+ area);+ area);}}elseelse System.out.println("Negative input");System.out.println("Negative input");
The if branch statement must be in a block because there are two of them.
There is only one else-branch statement. It does not need to be in a block, but you can if you want.
![Page 10: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/10.jpg)
Nested Nested ifif Statements Statements
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
![Page 11: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/11.jpg)
FlowChart for if – else if -- FlowChart for if – else if -- elseelse
Boolean test
statement(s) subordinate to if
Independent statement(s)
true
false
statement(s) subordinate to elseif
Boolean test
false
statement(s) subordinate to else
true
![Page 12: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/12.jpg)
Nesting an if - else Nesting an if - else inside the if portioninside the if portion
if (boolean expression1) if (boolean expression1) if (boolean expression2)if (boolean expression2)
statement1;statement1;elseelse
statement2;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.
![Page 13: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/13.jpg)
FlowChart for FlowChart for if if with nested if -- elsewith nested if -- else
Boolean test1
Independent statement(s)
false
true
statement1 subordinate to success on boolean test2. Therefore both tests succeeded.
Boolean test2
false
true
statement2 subordinate to success on boolean test2. Therefore test1 succeeded and test2 failed.
![Page 14: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/14.jpg)
Outer if-else with a Outer if-else with a nested if (no inner else)nested if (no inner else)
if (boolean expression1){ if (boolean expression1){ if (boolean expression2)if (boolean expression2)
statement1;statement1;}}elseelsestatement2;statement2;
The nested if.
NOTE: here, because of the braces, the else is associated with the if for boolean expression #1.
![Page 15: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/15.jpg)
FlowChart for FlowChart for if -elseif -elsewith nested ifwith nested if
Boolean test1
Independent statement(s)
false
statement1 subordinate to success on boolean test2. Therefore both tests succeeded.
Boolean test2
false
true
statement2 subordinate to failure of boolean test1 (the outer else).
true
![Page 16: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/16.jpg)
Shortcut Shortcut ifif Statements Statementsif (x > 0) if (x > 0)
y = 1y = 1else else y = -1;y = -1;
is equivalent tois equivalent to
y = (x > 0) ? 1 : -1;y = (x > 0) ? 1 : -1;
test
if
Returned if true
else
Returned if false
![Page 17: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/17.jpg)
switchswitch Statements Statementsswitch (switch (switch-expressionswitch-expression)){ { case case value1value1: :
statement(s) 1;statement(s) 1;break;break;
case case value2value2: : statement(s) 2;statement(s) 2;break;break;
… … case case valueNvalueN: interestRate = 9.0;: interestRate = 9.0;
statement(s) N;statement(s) N;break;break;
default: default: statement(s) for default;statement(s) for default;
}}
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.
No break needed for last condition
![Page 18: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/18.jpg)
switchswitch Statements Statementsswitch (status) {switch (status) { case 0: compute taxes for single filers;case 0: compute taxes for single filers; break;break; case 1: compute taxes for married file jointly;case 1: compute taxes for married file jointly; break;break; case 2: compute taxes for married file separately;case 2: compute taxes for married file separately; break;break; case 3: compute taxes for head of household;case 3: compute taxes for head of household; break;break; default: System.out.println("Errors: invalid status");default: System.out.println("Errors: invalid status"); System.exit(0);System.exit(0);}}
![Page 19: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/19.jpg)
switchswitch Statement Flow Statement Flow ChartChart
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
![Page 20: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/20.jpg)
EquivalentEquivalent if if statementstatementif (status == 0)if (status == 0)
compute tax for single filers;compute tax for single filers;
else if (status == 1)else if (status == 1)
compute tax for married filing jointly;compute tax for married filing jointly;
else if (status == 2)else if (status == 2)
compute tax for married filing separately;compute tax for married filing separately;
else if (status == 3)else if (status == 3)
compute tax for head of household;compute tax for head of household;
else{else{System.out.println(System.out.println(
("Errors: invalid status");("Errors: invalid status");System.exit(0);System.exit(0);
}}
![Page 21: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/21.jpg)
ExerciseExerciseif (a==1)if (a==1)
x += 6;x += 6;
else if (a == 2)else if (a == 2)
x += 10;x += 10;
else if (a == 3)else if (a == 3)
x += 16;x += 16;
else if (a == 4)else if (a == 4)
x += 34;x += 34;
Convert this if statement into a switch statement
![Page 22: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/22.jpg)
whilewhile Loops Loopswhile (continue-condition) while (continue-condition) {{ // loop-body;// loop-body;}}
Top-tested loopTest before performing statements of loop Loop body may never execute
![Page 23: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/23.jpg)
Listing 4.4 p109 – Listing 4.4 p109 – User Decides when to quitUser Decides when to quit
Initial data input – before the loop
Subsequent data inputs – toward the end of the loop body
![Page 24: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/24.jpg)
Do-whileDo-while Loops Loopsdodo{{ //loop body;//loop body;} while (continue-condition)} while (continue-condition)
Bottom-tested loopPerform statements of loop before testingAlways enter the loop body at least once
![Page 25: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/25.jpg)
Listing 4.5 – a Do-While Listing 4.5 – a Do-While LoopLoop
Test is at the bottom
![Page 26: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/26.jpg)
forfor Loops Loops
for (control variable initialization;for (control variable initialization; continue-test; continue-test;
adjustment-statement)adjustment-statement){{ //loop body;//loop body;}}
1) assignment statement
2) boolean expression
3) assignment statement
1) Set initial value for loop counter (only once, before looping starts)
2) Test loop counter (also called control variable) to see if it is less than the max loop allowed (before executing loop body)
3) Increment loop counter (after executing loop body) (usually an increment operator).
![Page 27: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/27.jpg)
forfor Loop Flow Chart Loop Flow Chart
![Page 28: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/28.jpg)
forfor Loop Example: Loop Example:
int i;int i;for (i = 0; i<100; i++) for (i = 0; i<100; i++) {{ System.out.println(“Hi. i is:” System.out.println(“Hi. i is:”
+ i); + i); }}
Here, the loop counter variable (called i ) is available for use outside the loop.
![Page 29: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/29.jpg)
Alternative Syntax:Alternative Syntax:Declare Loop Counter in Declare Loop Counter in
InitializationInitialization
for (int i = 0; i<100; i++) for (int i = 0; i<100; i++) {{ System.out.println(“Hi. i is:” System.out.println(“Hi. i is:”
+ i); + i); }}
Here, the loop counter variable (called i ) is available for use only within the loop.
![Page 30: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/30.jpg)
The Nested The Nested forfor Loop 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
Body of inner loop
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!
![Page 31: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/31.jpg)
Initialize outer loop counter
Initialize inner loop counter
Test to continue
outer loop
Test to continue
inner loop
Outer loop statement(s)
Outer loop statement(s)
Inner loop statement(s)
Increment outer loop counter
Increment inner loop counter
Statements preceding loop
Statements following loop
No
No
Yes
Yes
The Nested The Nested forfor Loop -- Loop --
FlowchartFlowchart
![Page 32: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/32.jpg)
Nested Loop ExampleNested Loop Example(my example)(my example)
Outer loop
Inner loop
![Page 33: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/33.jpg)
Example Program RunExample Program Run
![Page 34: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/34.jpg)
A couple points about the A couple points about the exampleexample
Max loop count value can be any numeric expression. Here it’s a variable
Special escape character \t for tab.
![Page 35: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/35.jpg)
Reminders about packages Reminders about packages from the examplefrom the example
The class NestedForLoop is in the package called controlStructurePackage.
Therefore, there is a file called NestedForLoop.class in a folder called controlStructurePackage.
![Page 36: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/36.jpg)
Reminders about packages Reminders about packages from the examplefrom 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.
![Page 37: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/37.jpg)
Another Example -- listing 4.6 p115Another Example -- listing 4.6 p115
![Page 38: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/38.jpg)
Listing 4.6Listing 4.6
Loop with single statement in body
![Page 39: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/39.jpg)
Listing 4.6Listing 4.6
An if statement nested inside a for loop, which is itself nested in another for loop.
![Page 40: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/40.jpg)
Listing 4.6Listing 4.6
At the end, the string is displayed in the output screen
Note: actions in the loops are concatenating values into the string output.
![Page 41: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/41.jpg)
Listing 4.6 program analysisListing 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?
![Page 42: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/42.jpg)
The The breakbreak Keyword Keyword
break can be used to terminate the loop based on decisions inside the loop body.
![Page 43: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/43.jpg)
Listing 4.11 Listing 4.11 Using the Using the break break keyword keyword
Question: how many times will this loop body execute?
What will be the value in sum?
![Page 44: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/44.jpg)
The The continuecontinue Keyword 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.
![Page 45: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/45.jpg)
Listing 4.12Listing 4.12Using the Using the continue continue keywordkeyword
Question 1: how many times will this loop body execute?
Question 2: how many times sum += number; execute?
![Page 46: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/46.jpg)
Typical Nested Structure: Decision within a LoopTypical Nested Structure: Decision within a Loop(menu-driven as first statement in loop)(menu-driven as first statement in loop)
User wants to
quit?
User choice 1?
Present menu options to userInput User
Choice
Choice 1 statement(s)
Statements following loop
No
Yes
Yes
User choice n?
Choice n statement(s)
Yes
No
No
![Page 47: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/47.jpg)
A Java ImplementationA Java Implementation
This implementation nests a switch inside a while loop.
Exercise:Exercise:Do the Do the same thing same thing by nesting by nesting an if an if statement statement inside a do-inside a do-while loop.while loop.
![Page 48: Control Structures Corresponds with Chapters 3 and 4](https://reader036.vdocuments.us/reader036/viewer/2022062304/56649ccb5503460f94993f05/html5/thumbnails/48.jpg)
Other Useful ExamplesOther Useful Examples
Listing 4.8: finding the greatest common Listing 4.8: finding the greatest common divisor (while loop with nested if statement)divisor (while loop with nested if statement)
Listing 4.9: finding a sales amount (do-while Listing 4.9: finding a sales amount (do-while loop with nested if - else if - else statement)loop with nested if - else if - else statement)
Listing 4.10: printing a pyramid (outer for Listing 4.10: printing a pyramid (outer for loop with three nested for loops inside it)loop with three nested for loops inside it)
Listing 4.14: finding prime numbers (outer Listing 4.14: finding prime numbers (outer while loop with nested for loop with nested if while loop with nested for loop with nested if statement)statement)