SlideShare a Scribd company logo
© 2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 5 – Control Structures: Part 2
Outline
5.1 Introduction
5.2 Essentials of Counter-Controlled Repetition
5.3 for Repetition Statement
5.4 Examples Using the for Statement
5.5 do…while Repetition Statement
5.6 switch Multiple-Selection Statement
5.7 break and continue Statements
5.8 Labeled break and continue Statements
5.9 Logical Operators
5.10 Structured Programming Summary
5.11 (Optional Case Study) Thinking About Objects: Identifying
Objects’ States and Activities
© 2003 Prentice Hall, Inc. All rights reserved.
2
5.1 Introduction
• Continue structured-programming discussion
– Introduce Java’s remaining control structures
© 2003 Prentice Hall, Inc. All rights reserved.
3
5.2 Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires:
– Control variable (loop counter)
– Initial value of the control variable
– Increment/decrement of control variable through each loop
– Condition that tests for the final value of the control variable
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
4
WhileCounter.ja
va
Line 14
Line 16
Line 18
1 // Fig. 5.1: WhileCounter.java
2 // Counter-controlled repetition.
3 import java.awt.Graphics;
4
5 import javax.swing.JApplet;
6
7 public class WhileCounter extends JApplet {
8
9 // draw lines on applet’s background
10 public void paint( Graphics g )
11 {
12 super.paint( g ); // call paint method inherited from JApplet
13
14 int counter = 1; // initialization
15
16 while ( counter <= 10 ) { // repetition condition
17 g.drawLine( 10, 10, 250, counter * 10 );
18 ++counter; // increment
19
20 } // end while
21
22 } // end method paint
23
24 } // end class WhileCounter
Increment for counter
Condition tests for
counter’s final value
Control-variable name is counter
Control-variable initial value is 1
© 2003 Prentice Hall, Inc. All rights reserved.
5
5.3 for Repetition Statement
• Handles counter-controlled-repetition details
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
6
ForCounter.java
Line 16
int counter =
1;
Line 16
counter <= 10;
Line 16
counter++;
1 // Fig. 5.2: ForCounter.java
2 // Counter-controlled repetition with the for statement.
3 import java.awt.Graphics;
4
5 import javax.swing.JApplet;
6
7 public class ForCounter extends JApplet {
8
9 // draw lines on applet’s background
10 public void paint( Graphics g )
11 {
12 super.paint( g ); // call paint method inherited from JApplet
13
14 // for statement header includes initialization,
15 // repetition condition and increment
16 for ( int counter = 1; counter <= 10; counter++ )
17 g.drawLine( 10, 10, 250, counter * 10 );
18
19 } // end method paint
20
21 } // end class ForCounter
Condition tests for
counter’s final valueControl-variable name is counter
Control-variable initial value is 1
Increment for counter
© 2003 Prentice Hall, Inc. All rights reserved.
7
Fig. 5.3 for statement header components.
for ( int counter = 1; counter <= 10; counter++ )
Increment of control
variable
Control
variable
Final value of control
variable for which the
condition is true
for
keyword
Loop-continuation
condition
Initial value of
control variable
Required
semicolon
separator
Required
semicolon
separator
© 2003 Prentice Hall, Inc. All rights reserved.
8
5.3 for Repetition Structure (cont.)
for ( initialization; loopContinuationCondition; increment )
statement;
can usually be rewritten as:
initialization;
while ( loopContinuationCondition ) {
statement;
increment;
}
© 2003 Prentice Hall, Inc. All rights reserved.
9
Fig. 5.4 for statement activity diagram.
[counter <= 10]
[counter > 10]
int counter = 1
counter++Determine whether
the final value of
control variable has
been reached
g.drawLine(
10, 10, 250,
counter * 10 );
Establish initial value of
control variable
Draw a line on the
applet
Increment the
control variable
© 2003 Prentice Hall, Inc. All rights reserved.
10
5.4 Examples Using the for Statement
• Varying control variable in for statement
– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in increments of –1
• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in increments of 7
• for ( int i = 7; i <= 77; i += 7 )
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
11
Sum.java
Line 12
1 // Fig. 5.5: Sum.java
2 // Summing integers with the for statement.
3 import javax.swing.JOptionPane;
4
5 public class Sum {
6
7 public static void main( String args[] )
8 {
9 int total = 0; // initialize sum
10
11 // total even integers from 2 through 100
12 for ( int number = 2; number <= 100; number += 2 )
13 total += number;
14
15 // display results
16 JOptionPane.showMessageDialog( null, "The sum is " + total,
17 "Total Even Integers from 2 to 100",
18 JOptionPane.INFORMATION_MESSAGE );
19
20 System.exit( 0 ); // terminate application
21
22 } // end main
23
24 } // end class Sum
increment number by 2 each iteration
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
12
Interest.java
Lines 13-15
Line 18
Line 19
1 // Fig. 5.6: Interest.java
2 // Calculating compound interest.
3 import java.text.NumberFormat; // class for numeric formatting
4 import java.util.Locale; // class for country-specific information
5
6 import javax.swing.JOptionPane;
7 import javax.swing.JTextArea;
8
9 public class Interest {
10
11 public static void main( String args[] )
12 {
13 double amount; // amount on deposit at end of each year
14 double principal = 1000.0; // initial amount before interest
15 double rate = 0.05; // interest rate
16
17 // create NumberFormat for currency in US dollar format
18 NumberFormat moneyFormat =
19 NumberFormat.getCurrencyInstance( Locale.US );
20
21 // create JTextArea to display output
22 JTextArea outputTextArea = new JTextArea();
23
24 // set first line of text in outputTextArea
25 outputTextArea.setText( "YeartAmount on depositn" );
26
Java treats floating-points as
type double
NumberFormat can format
numeric values as currency
Display currency values with
dollar sign ($)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
13
Interest.java
Lines 28-31
27 // calculate amount on deposit for each of ten years
28 for ( int year = 1; year <= 10; year++ ) {
29
30 // calculate new amount for specified year
31 amount = principal * Math.pow( 1.0 + rate, year );
32
33 // append one line of text to outputTextArea
34 outputTextArea.append( year + "t" +
35 moneyFormat.format( amount ) + "n" );
36
37 } // end for
38
39 // display results
40 JOptionPane.showMessageDialog( null, outputTextArea,
41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE );
42
43 System.exit( 0 ); // terminate the application
44
45 } // end main
46
47 } // end class Interest
Calculate amount with for
statement
© 2003 Prentice Hall, Inc. All rights reserved.
14
5.5 do…while Repetition Statement
• do…while structure
– Similar to while structure
– Tests loop-continuation after performing body of loop
• i.e., loop body always executes at least once
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
15
DoWhileTest.jav
a
Lines 16-20
1 // Fig. 5.7: DoWhileTest.java
2 // Using the do...while statement.
3 import java.awt.Graphics;
4
5 import javax.swing.JApplet;
6
7 public class DoWhileTest extends JApplet {
8
9 // draw lines on applet
10 public void paint( Graphics g )
11 {
12 super.paint( g ); // call paint method inherited from JApplet
13
14 int counter = 1; // initialize counter
15
16 do {
17 g.drawOval( 110 - counter * 10, 110 - counter * 10,
18 counter * 20, counter * 20 );
19 ++counter;
20 } while ( counter <= 10 ); // end do...while
21
22 } // end method paint
23
24 } // end class DoWhileTest
Oval is drawn before testing
counter’s final value
© 2003 Prentice Hall, Inc. All rights reserved.
16
Fig. 5.8 do…while repetition statement activity diagram.
action state
[true]
[false]
condition
© 2003 Prentice Hall, Inc. All rights reserved.
17
5.6 switch Multiple-Selection Statement
• switch statement
– Used for multiple selections
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
18
SwitchTest.java
Lines 16-21:
Getting user’s input
1 // Fig. 5.9: SwitchTest.java
2 // Drawing lines, rectangles or ovals based on user input.
3 import java.awt.Graphics;
4
5 import javax.swing.*;
6
7 public class SwitchTest extends JApplet {
8 int choice; // user's choice of which shape to draw
9
10 // initialize applet by obtaining user's choice
11 public void init()
12 {
13 String input; // user's input
14
15 // obtain user's choice
16 input = JOptionPane.showInputDialog(
17 "Enter 1 to draw linesn" +
18 "Enter 2 to draw rectanglesn" +
19 "Enter 3 to draw ovalsn" );
20
21 choice = Integer.parseInt( input ); // convert input to int
22
23 } // end method init
24
25 // draw shapes on applet's background
26 public void paint( Graphics g )
27 {
28 super.paint( g ); // call paint method inherited from JApplet
29
30 for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9)
31
Get user’s input in JApplet
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
19
SwitchTest.java
Line 32:
controlling
expression
Line 32:
switch statement
Line 48
32 switch ( choice ) { // determine shape to draw
33
34 case 1: // draw a line
35 g.drawLine( 10, 10, 250, 10 + i * 10 );
36 break; // done processing case
37
38 case 2: // draw a rectangle
39 g.drawRect( 10 + i * 10, 10 + i * 10,
40 50 + i * 10, 50 + i * 10 );
41 break; // done processing case
42
43 case 3: // draw an oval
44 g.drawOval( 10 + i * 10, 10 + i * 10,
45 50 + i * 10, 50 + i * 10 );
46 break; // done processing case
47
48 default: // draw string indicating invalid value entered
49 g.drawString( "Invalid value entered",
50 10, 20 + i * 15 );
51
52 } // end switch
53
54 } // end for
55
56 } // end method paint
57
58 } // end class SwitchTest
default case for invalid entries
switch statement determines
which case label to execute,
depending on controlling expression
user input (choice) is
controlling expression
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
20
SwitchTest.java
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
21
SwitchTest.java
© 2003 Prentice Hall, Inc. All rights reserved.
22
Fig. 5.10 switch multiple-selection statement activity diagram with break statements.
case a action(s) break
default action(s)
[true]
case b action(s) break
case z action(s) break
.
.
.
[false]
case a
[true]
[true]
case b
case z
[false]
[false]
© 2003 Prentice Hall, Inc. All rights reserved.
23
5.7 break and continue Statements
• break/continue
– Alter flow of control
• break statement
– Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
• continue statement
– Skips remaining statements in loop body
– Proceeds to next iteration
• Used in while, for or do…while statements
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
24
BreakTest.java
Line 12
Lines 14-15
1 // Fig. 5.11: BreakTest.java
2 // Terminating a loop with break.
3 import javax.swing.JOptionPane;
4
5 public class BreakTest {
6
7 public static void main( String args[] )
8 {
9 String output = "";
10 int count;
11
12 for ( count = 1; count <= 10; count++ ) { // loop 10 times
13
14 if ( count == 5 ) // if count is 5,
15 break; // terminate loop
16
17 output += count + " ";
18
19 } // end for
20
21 output += "nBroke out of loop at count = " + count;
22 JOptionPane.showMessageDialog( null, output );
23
24 System.exit( 0 ); // terminate application
25
26 } // end main
27
28 } // end class BreakTest
Loop 10 times
exit for structure (break)
when count equals 5
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
25
ContinueTest.ja
va
Line 11
Lines 13-14
1 // Fig. 5.12: ContinueTest.java
2 // Continuing with the next iteration of a loop.
3 import javax.swing.JOptionPane;
4
5 public class ContinueTest {
6
7 public static void main( String args[] )
8 {
9 String output = "";
10
11 for ( int count = 1; count <= 10; count++ ) { // loop 10 times
12
13 if ( count == 5 ) // if count is 5,
14 continue; // skip remaining code in loop
15
16 output += count + " ";
17
18 } // end for
19
20 output += "nUsed continue to skip printing 5";
21 JOptionPane.showMessageDialog( null, output );
22
23 System.exit( 0 ); // terminate application
24
25 } // end main
26
27 } // end class ContinueTest
Loop 10 times
Skip line 16 and proceed to
line 11 when count equals 5
© 2003 Prentice Hall, Inc. All rights reserved.
26
5.8 Labeled break and continue
Statements
• Labeled block
– Set of statements enclosed by {}
– Preceded by a label
• Labeled break statement
– Exit from nested control structures
– Proceeds to end of specified labeled block
• Labeled continue statement
– Skips remaining statements in nested-loop body
– Proceeds to beginning of specified labeled block
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
27
BreakLabelTest.
java
Line 11
Line 14
Line 17
Lines 19-20
1 // Fig. 5.13: BreakLabelTest.java
2 // Labeled break statement.
3 import javax.swing.JOptionPane;
4
5 public class BreakLabelTest {
6
7 public static void main( String args[] )
8 {
9 String output = "";
10
11 stop: { // labeled block
12
13 // count 10 rows
14 for ( int row = 1; row <= 10; row++ ) {
15
16 // count 5 columns
17 for ( int column = 1; column <= 5 ; column++ ) {
18
19 if ( row == 5 ) // if row is 5,
20 break stop; // jump to end of stop block
21
22 output += "* ";
23
24 } // end inner for
25
26 output += "n";
27
28 } // end outer for
29
Loop 10 times
stop is the labeled block
Exit to line 35 (next slide)
Nested loop 5 times
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
28
BreakLabelTest.
java
30 // following line is skipped
31 output += "nLoops terminated normally";
32
33 } // end labeled block
34
35 JOptionPane.showMessageDialog( null, output,
36 "Testing break with a label",
37 JOptionPane.INFORMATION_MESSAGE );
38
39 System.exit( 0 ); // terminate application
40
41 } // end main
42
43 } // end class BreakLabelTest
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
29
ContinueLabelTe
st.java
Line 11
Line 14
Line 17
Lines 21-22
1 // Fig. 5.14: ContinueLabelTest.java
2 // Labeled continue statement.
3 import javax.swing.JOptionPane;
4
5 public class ContinueLabelTest {
6
7 public static void main( String args[] )
8 {
9 String output = "";
10
11 nextRow: // target label of continue statement
12
13 // count 5 rows
14 for ( int row = 1; row <= 5; row++ ) {
15 output += "n";
16
17 // count 10 columns per row
18 for ( int column = 1; column <= 10; column++ ) {
19
20 // if column greater than row, start next row
21 if ( column > row )
22 continue nextRow; // next iteration of labeled loop
23
24 output += "* ";
25
26 } // end inner for
27
28 } // end outer for
nextRow is the labeled block
Loop 5 times
Nested loop 10 times
continue to line 11 (nextRow)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
30
ContinueLabelTe
st.java
29
30 JOptionPane.showMessageDialog( null, output,
31 "Testing continue with a label",
32 JOptionPane.INFORMATION_MESSAGE );
33
34 System.exit( 0 ); // terminate application
35
36 } // end main
37
38 } // end class ContinueLabelTest
© 2003 Prentice Hall, Inc. All rights reserved.
31
5.9 Logical Operators
• Logical operators
– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators
– && (conditional AND)
– & (boolean logical AND)
– || (conditional OR)
– | (boolean logical inclusive OR)
– ^ (boolean logical exclusive OR)
– ! (logical NOT)
© 2003 Prentice Hall, Inc. All rights reserved.
32
expression1 expression2 expression1 &&
expression2
false false false
false true false
true false false
true true true
Fig. 5.15 && (conditional AND) operator truth table.
expression1 expression2 expression1 ||
expression2
false false false
false true true
true false true
true true true
Fig. 5.16 || (conditional OR) operator truth table.
© 2003 Prentice Hall, Inc. All rights reserved.
33
expression1 expression2 expression1 ^
expression2
false false false
false true true
true false true
true true false
Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table.
expression !expression
false true
true false
Fig. 5.18 ! (logical negation, or logical NOT) operator truth table.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
34
LogicalOperator
s.java
Lines 16-20
Lines 23-27
1 // Fig. 5.19: LogicalOperators.java
2 // Logical operators.
3 import javax.swing.*;
4
5 public class LogicalOperators
6
7 public static void main( String args[] )
8 {
9 // create JTextArea to display results
10 JTextArea outputArea = new JTextArea( 17, 20 );
11
12 // attach JTextArea to a JScrollPane so user can scroll results
13 JScrollPane scroller = new JScrollPane( outputArea );
14
15 // create truth table for && (conditional AND) operator
16 String output = "Logical AND (&&)" +
17 "nfalse && false: " + ( false && false ) +
18 "nfalse && true: " + ( false && true ) +
19 "ntrue && false: " + ( true && false ) +
20 "ntrue && true: " + ( true && true );
21
22 // create truth table for || (conditional OR) operator
23 output += "nnLogical OR (||)" +
24 "nfalse || false: " + ( false || false ) +
25 "nfalse || true: " + ( false || true ) +
26 "ntrue || false: " + ( true || false ) +
27 "ntrue || true: " + ( true || true );
28
Conditional AND truth table
Conditional OR truth table
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
35
LogicalOperator
s.java
Lines 30-34
Lines 37-41
Lines 44-48
Lines 51-53
29 // create truth table for & (boolean logical AND) operator
30 output += "nnBoolean logical AND (&)" +
31 "nfalse & false: " + ( false & false ) +
32 "nfalse & true: " + ( false & true ) +
33 "ntrue & false: " + ( true & false ) +
34 "ntrue & true: " + ( true & true );
35
36 // create truth table for | (boolean logical inclusive OR) operator
37 output += "nnBoolean logical inclusive OR (|)" +
38 "nfalse | false: " + ( false | false ) +
39 "nfalse | true: " + ( false | true ) +
40 "ntrue | false: " + ( true | false ) +
41 "ntrue | true: " + ( true | true );
42
43 // create truth table for ^ (boolean logical exclusive OR) operator
44 output += "nnBoolean logical exclusive OR (^)" +
45 "nfalse ^ false: " + ( false ^ false ) +
46 "nfalse ^ true: " + ( false ^ true ) +
47 "ntrue ^ false: " + ( true ^ false ) +
48 "ntrue ^ true: " + ( true ^ true );
49
50 // create truth table for ! (logical negation) operator
51 output += "nnLogical NOT (!)" +
52 "n!false: " + ( !false ) +
53 "n!true: " + ( !true );
54
55 outputArea.setText( output ); // place results in JTextArea
56
Logical NOT truth table
Boolean logical exclusive
OR truth table
Boolean logical inclusive
OR truth table
Boolean logical AND
truth table
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
36
LogicalOperator
s.java
57 JOptionPane.showMessageDialog( null, scroller,
58 "Truth Tables", JOptionPane.INFORMATION_MESSAGE );
59
60 System.exit( 0 ); // terminate application
61
62 } // end main
63
64 } // end class LogicalOperators
© 2003 Prentice Hall, Inc. All rights reserved.
37
Operators Associativity Type
++ -- right to left unary postfix
++ -- + - !
(type)
right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
& left to right boolean logical AND
^ left to right boolean logical exclusive OR
| left to right boolean logical inclusive OR
&& left to right conditional AND
|| left to right conditional OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 5.20 Precedence/associativity of the operators discussed so far.
© 2003 Prentice Hall, Inc. All rights reserved.
38
5.10 Structured Programming Summary
• Sequence structure
– “built-in” to Java
• Selection structure
– if, if…else and switch
• Repetition structure
– while, do…while and for
© 2003 Prentice Hall, Inc. All rights reserved.
39
Fig. 5.21 Java’s single-entry/single-exit sequence, selection and repetition statements.
[t]
[f]
[f]
[t]
break
break
[t]
break
[t]
[f]
[t]
[f]
[t]
[f]
[t]
[f]
Repetition
while statement do while statement for statement
SelectionSequence
if else statement
(double selection)
if statement (single
selection)
switch statement
(multiple selection)
.
.
.
[t][f]
default
© 2003 Prentice Hall, Inc. All rights reserved.
40
Rules for Forming Structured Programs
1)
Begin with the “simplest activity diagram” (Fig. 5.23).
2)
Any action state can be replaced by two action states in sequence.
3)
Any action state can be replaced by any control statement (sequence,
if, if else, switch, while, do while or for).
4)
Rules 2 and 3 can be applied as often as you like and in any order.
Fig. 5.22 Rules for forming structured programs.
action state
Fig. 5.23 Simplest activity diagram.
© 2003 Prentice Hall, Inc. All rights reserved.
41
Fig. 5.24 Repeatedly applying rule 2 of Fig. 5.22 to the simplest activity diagram.
.
.
.action state
action state
apply
Rule 2
apply
Rule 2
apply
Rule 2
action state
action state
action state
action state
action state
action state
© 2003 Prentice Hall, Inc. All rights reserved.
42
Fig. 5.25 Applying rule 3 of Fig. 5.22 to the simplest activity diagram.
action state
apply
Rule 3
apply
Rule 3
apply
Rule 3 action stateaction state
action stateaction state action stateaction state
[f] [t]
[f] [t]
[f] [t][f] [t]
© 2003 Prentice Hall, Inc. All rights reserved.
43
Fig. 5.26 Activity diagram with illegal syntax.
action state
action state
action state
action state
© 2003 Prentice Hall, Inc. All rights reserved.
445.11 (Optional Case Study) Thinking About
Objects: Identifying Objects’ States and
Activities
• State
– Describes an object’s condition at a given time
• Statechart diagram (UML)
– Express how an object can change state
– Express under what conditions an object can change state
– Diagram notation (Fig. 5.28)
• States are represented by rounded rectangles
– e.g., “Not Pressed” and “Pressed”
• Solid circle (with attached arrowhead) designates initial state
• Arrows represent transitions (state changes)
– Objects change state in response to messages
• e.g., “buttonPressed” and “buttonReset”
© 2003 Prentice Hall, Inc. All rights reserved.
45
Fig. 5.27 Statechart diagram for FloorButton and ElevatorButton objects.
buttonReset
buttonPressed
PressedNot pressed
© 2003 Prentice Hall, Inc. All rights reserved.
465.11 (Optional Case Study) Thinking About
Objects: Identifying Objects’ States and
Activities (cont.):
• Activity diagram (UML)
– Models an object’s workflow during program execution
– Models the actions that an object will perform
– Diagram notation (Fig. 5.28)
• Activities are represented by ovals
• Solid circle designates initial activity
• Arrows represents transitions between activities
• Small diamond represents branch
– Next transition at branch is based on guard condition
© 2003 Prentice Hall, Inc. All rights reserved.
47
Fig. 5.28 Activity diagram for a Person object.
[floor door closed]
press elevator button
enter elevator
move toward floor button
wait for door to open
press floor button
wait for door to open
[floor door open]
exit elevator
wait for passenger to exit elevator
[passenger on elevator]
[no passenger on
elevator]
© 2003 Prentice Hall, Inc. All rights reserved.
48
Fig. 5.29 Activity diagram for the Elevator object.
close elevator door
ring bell
reset elevator button
[elevator idle][button on destination
floor
pressed]
open elevator door
[elevator moving]
[button on
current floor
pressed]
[floor button
pressed]
[elevator button
pressed]
[summoned]
[not summoned]
set summoned to true
set summoned to false
move to destination floor
[button on
destination
floor
pressed]
[button on
current floor
pressed]

More Related Content

What's hot

Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
Durgadevi palani
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionstemkin abdlkader
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3
Naveen Kumar
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
HUST
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2
Naveen Kumar
 
Csphtp1 15
Csphtp1 15Csphtp1 15
Csphtp1 15
HUST
 
VERILOG CODE
VERILOG CODEVERILOG CODE
VERILOG CODE
Dhaval Kaneria
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
Scilab
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
NUST Stuff
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2IIUM
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
NUST Stuff
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16HUST
 
Circles graphic
Circles graphicCircles graphic
Circles graphic
alldesign
 
stack
stackstack
stack
Raj Sarode
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul Haseeb
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6
Abdul Haseeb
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 

What's hot (20)

Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functions
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2
 
Csphtp1 15
Csphtp1 15Csphtp1 15
Csphtp1 15
 
VERILOG CODE
VERILOG CODEVERILOG CODE
VERILOG CODE
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16
 
Circles graphic
Circles graphicCircles graphic
Circles graphic
 
stack
stackstack
stack
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6
 
C++ Language
C++ LanguageC++ Language
C++ Language
 

Similar to Control Structures: Part 2

Lecture#5 Operators in C++
Lecture#5 Operators in C++Lecture#5 Operators in C++
Lecture#5 Operators in C++
NUST Stuff
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
IEEE MIU SB
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S Guide
Stephen Chin
 
Introduction to ES2015
Introduction to ES2015Introduction to ES2015
Introduction to ES2015
kiranabburi
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
Hermann Hueck
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Verilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONSVerilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONS
Dr.YNM
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
جامعة القدس المفتوحة
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
rafbolet0
 
Control structure
Control structureControl structure
Control structure
Liam Delector
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structures
sandhyakiran10
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
Sameer Wadkar
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 

Similar to Control Structures: Part 2 (20)

Lecture#5 Operators in C++
Lecture#5 Operators in C++Lecture#5 Operators in C++
Lecture#5 Operators in C++
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
4. programing 101
4. programing 1014. programing 101
4. programing 101
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S Guide
 
Introduction to ES2015
Introduction to ES2015Introduction to ES2015
Introduction to ES2015
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Verilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONSVerilog TASKS & FUNCTIONS
Verilog TASKS & FUNCTIONS
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
 
Control structure
Control structureControl structure
Control structure
 
04.ppt
04.ppt04.ppt
04.ppt
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structures
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
functions
functionsfunctions
functions
 

More from Andy Juan Sarango Veliz

Examen final de CCNA Routing y Switching Academia OW
Examen final de CCNA Routing y Switching  Academia OWExamen final de CCNA Routing y Switching  Academia OW
Examen final de CCNA Routing y Switching Academia OW
Andy Juan Sarango Veliz
 
Criptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de SeguridadCriptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de Seguridad
Andy Juan Sarango Veliz
 
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador WebAlfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador Web
Andy Juan Sarango Veliz
 
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos BásicosAlfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos Básicos
Andy Juan Sarango Veliz
 
Alfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos BásicosAlfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
Andy Juan Sarango Veliz
 
Gestión y Operación de la Ciberseguridad
Gestión y Operación de la CiberseguridadGestión y Operación de la Ciberseguridad
Gestión y Operación de la Ciberseguridad
Andy Juan Sarango Veliz
 
Tecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de serviciosTecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de servicios
Andy Juan Sarango Veliz
 
3. wordpress.org
3. wordpress.org3. wordpress.org
3. wordpress.org
Andy Juan Sarango Veliz
 
2. wordpress.com
2. wordpress.com2. wordpress.com
2. wordpress.com
Andy Juan Sarango Veliz
 
1. Introducción a Wordpress
1. Introducción a Wordpress1. Introducción a Wordpress
1. Introducción a Wordpress
Andy Juan Sarango Veliz
 
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Andy Juan Sarango Veliz
 
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Andy Juan Sarango Veliz
 
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital ISoftware Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital I
Andy Juan Sarango Veliz
 
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FMSoftware Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FM
Andy Juan Sarango Veliz
 
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AMSoftware Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AM
Andy Juan Sarango Veliz
 
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio CompanionSoftware Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio Companion
Andy Juan Sarango Veliz
 
Software Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: IntroducciónSoftware Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: Introducción
Andy Juan Sarango Veliz
 
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
Andy Juan Sarango Veliz
 
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generaciónLos cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Andy Juan Sarango Veliz
 
ITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 EditionITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 Edition
Andy Juan Sarango Veliz
 

More from Andy Juan Sarango Veliz (20)

Examen final de CCNA Routing y Switching Academia OW
Examen final de CCNA Routing y Switching  Academia OWExamen final de CCNA Routing y Switching  Academia OW
Examen final de CCNA Routing y Switching Academia OW
 
Criptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de SeguridadCriptología de empleo en el Esquema Nacional de Seguridad
Criptología de empleo en el Esquema Nacional de Seguridad
 
Alfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador WebAlfabetización Informática - 3. Navegador Web
Alfabetización Informática - 3. Navegador Web
 
Alfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos BásicosAlfabetización Informática - 2. Test de Conceptos Básicos
Alfabetización Informática - 2. Test de Conceptos Básicos
 
Alfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos BásicosAlfabetización Informática - 1. Conceptos Básicos
Alfabetización Informática - 1. Conceptos Básicos
 
Gestión y Operación de la Ciberseguridad
Gestión y Operación de la CiberseguridadGestión y Operación de la Ciberseguridad
Gestión y Operación de la Ciberseguridad
 
Tecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de serviciosTecnologías de virtualización y despliegue de servicios
Tecnologías de virtualización y despliegue de servicios
 
3. wordpress.org
3. wordpress.org3. wordpress.org
3. wordpress.org
 
2. wordpress.com
2. wordpress.com2. wordpress.com
2. wordpress.com
 
1. Introducción a Wordpress
1. Introducción a Wordpress1. Introducción a Wordpress
1. Introducción a Wordpress
 
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
Redes de Computadores: Un enfoque descendente 7.° Edición - Capítulo 9
 
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
Análisis e Implementación de una Red "SDN" usando controladores "Open Source"
 
Software Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital ISoftware Defined Radio - Capítulo 5: Modulación Digital I
Software Defined Radio - Capítulo 5: Modulación Digital I
 
Software Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FMSoftware Defined Radio - Capítulo 4: Modulación FM
Software Defined Radio - Capítulo 4: Modulación FM
 
Software Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AMSoftware Defined Radio - Capítulo 3: Modulación AM
Software Defined Radio - Capítulo 3: Modulación AM
 
Software Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio CompanionSoftware Defined Radio - Capítulo 2: GNU Radio Companion
Software Defined Radio - Capítulo 2: GNU Radio Companion
 
Software Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: IntroducciónSoftware Defined Radio - Capítulo 1: Introducción
Software Defined Radio - Capítulo 1: Introducción
 
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
MAE-RAV-ROS Introducción a Ruteo Avanzado con MikroTik RouterOS v6.42.5.01
 
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generaciónLos cuatro desafíos de ciberseguridad más críticos de nuestra generación
Los cuatro desafíos de ciberseguridad más críticos de nuestra generación
 
ITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 EditionITIL Foundation ITIL 4 Edition
ITIL Foundation ITIL 4 Edition
 

Recently uploaded

DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
ambekarshweta25
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 

Recently uploaded (20)

DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 

Control Structures: Part 2

  • 1. © 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 for Repetition Statement 5.4 Examples Using the for Statement 5.5 do…while Repetition Statement 5.6 switch Multiple-Selection Statement 5.7 break and continue Statements 5.8 Labeled break and continue Statements 5.9 Logical Operators 5.10 Structured Programming Summary 5.11 (Optional Case Study) Thinking About Objects: Identifying Objects’ States and Activities
  • 2. © 2003 Prentice Hall, Inc. All rights reserved. 2 5.1 Introduction • Continue structured-programming discussion – Introduce Java’s remaining control structures
  • 3. © 2003 Prentice Hall, Inc. All rights reserved. 3 5.2 Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires: – Control variable (loop counter) – Initial value of the control variable – Increment/decrement of control variable through each loop – Condition that tests for the final value of the control variable
  • 4. © 2003 Prentice Hall, Inc. All rights reserved. Outline 4 WhileCounter.ja va Line 14 Line 16 Line 18 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class WhileCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet 13 14 int counter = 1; // initialization 15 16 while ( counter <= 10 ) { // repetition condition 17 g.drawLine( 10, 10, 250, counter * 10 ); 18 ++counter; // increment 19 20 } // end while 21 22 } // end method paint 23 24 } // end class WhileCounter Increment for counter Condition tests for counter’s final value Control-variable name is counter Control-variable initial value is 1
  • 5. © 2003 Prentice Hall, Inc. All rights reserved. 5 5.3 for Repetition Statement • Handles counter-controlled-repetition details
  • 6. © 2003 Prentice Hall, Inc. All rights reserved. Outline 6 ForCounter.java Line 16 int counter = 1; Line 16 counter <= 10; Line 16 counter++; 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class ForCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet 13 14 // for statement header includes initialization, 15 // repetition condition and increment 16 for ( int counter = 1; counter <= 10; counter++ ) 17 g.drawLine( 10, 10, 250, counter * 10 ); 18 19 } // end method paint 20 21 } // end class ForCounter Condition tests for counter’s final valueControl-variable name is counter Control-variable initial value is 1 Increment for counter
  • 7. © 2003 Prentice Hall, Inc. All rights reserved. 7 Fig. 5.3 for statement header components. for ( int counter = 1; counter <= 10; counter++ ) Increment of control variable Control variable Final value of control variable for which the condition is true for keyword Loop-continuation condition Initial value of control variable Required semicolon separator Required semicolon separator
  • 8. © 2003 Prentice Hall, Inc. All rights reserved. 8 5.3 for Repetition Structure (cont.) for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; }
  • 9. © 2003 Prentice Hall, Inc. All rights reserved. 9 Fig. 5.4 for statement activity diagram. [counter <= 10] [counter > 10] int counter = 1 counter++Determine whether the final value of control variable has been reached g.drawLine( 10, 10, 250, counter * 10 ); Establish initial value of control variable Draw a line on the applet Increment the control variable
  • 10. © 2003 Prentice Hall, Inc. All rights reserved. 10 5.4 Examples Using the for Statement • Varying control variable in for statement – Vary control variable from 1 to 100 in increments of 1 • for ( int i = 1; i <= 100; i++ ) – Vary control variable from 100 to 1 in increments of –1 • for ( int i = 100; i >= 1; i-- ) – Vary control variable from 7 to 77 in increments of 7 • for ( int i = 7; i <= 77; i += 7 )
  • 11. © 2003 Prentice Hall, Inc. All rights reserved. Outline 11 Sum.java Line 12 1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3 import javax.swing.JOptionPane; 4 5 public class Sum { 6 7 public static void main( String args[] ) 8 { 9 int total = 0; // initialize sum 10 11 // total even integers from 2 through 100 12 for ( int number = 2; number <= 100; number += 2 ) 13 total += number; 14 15 // display results 16 JOptionPane.showMessageDialog( null, "The sum is " + total, 17 "Total Even Integers from 2 to 100", 18 JOptionPane.INFORMATION_MESSAGE ); 19 20 System.exit( 0 ); // terminate application 21 22 } // end main 23 24 } // end class Sum increment number by 2 each iteration
  • 12. © 2003 Prentice Hall, Inc. All rights reserved. Outline 12 Interest.java Lines 13-15 Line 18 Line 19 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest. 3 import java.text.NumberFormat; // class for numeric formatting 4 import java.util.Locale; // class for country-specific information 5 6 import javax.swing.JOptionPane; 7 import javax.swing.JTextArea; 8 9 public class Interest { 10 11 public static void main( String args[] ) 12 { 13 double amount; // amount on deposit at end of each year 14 double principal = 1000.0; // initial amount before interest 15 double rate = 0.05; // interest rate 16 17 // create NumberFormat for currency in US dollar format 18 NumberFormat moneyFormat = 19 NumberFormat.getCurrencyInstance( Locale.US ); 20 21 // create JTextArea to display output 22 JTextArea outputTextArea = new JTextArea(); 23 24 // set first line of text in outputTextArea 25 outputTextArea.setText( "YeartAmount on depositn" ); 26 Java treats floating-points as type double NumberFormat can format numeric values as currency Display currency values with dollar sign ($)
  • 13. © 2003 Prentice Hall, Inc. All rights reserved. Outline 13 Interest.java Lines 28-31 27 // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) { 29 30 // calculate new amount for specified year 31 amount = principal * Math.pow( 1.0 + rate, year ); 32 33 // append one line of text to outputTextArea 34 outputTextArea.append( year + "t" + 35 moneyFormat.format( amount ) + "n" ); 36 37 } // end for 38 39 // display results 40 JOptionPane.showMessageDialog( null, outputTextArea, 41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); 42 43 System.exit( 0 ); // terminate the application 44 45 } // end main 46 47 } // end class Interest Calculate amount with for statement
  • 14. © 2003 Prentice Hall, Inc. All rights reserved. 14 5.5 do…while Repetition Statement • do…while structure – Similar to while structure – Tests loop-continuation after performing body of loop • i.e., loop body always executes at least once
  • 15. © 2003 Prentice Hall, Inc. All rights reserved. Outline 15 DoWhileTest.jav a Lines 16-20 1 // Fig. 5.7: DoWhileTest.java 2 // Using the do...while statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class DoWhileTest extends JApplet { 8 9 // draw lines on applet 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet 13 14 int counter = 1; // initialize counter 15 16 do { 17 g.drawOval( 110 - counter * 10, 110 - counter * 10, 18 counter * 20, counter * 20 ); 19 ++counter; 20 } while ( counter <= 10 ); // end do...while 21 22 } // end method paint 23 24 } // end class DoWhileTest Oval is drawn before testing counter’s final value
  • 16. © 2003 Prentice Hall, Inc. All rights reserved. 16 Fig. 5.8 do…while repetition statement activity diagram. action state [true] [false] condition
  • 17. © 2003 Prentice Hall, Inc. All rights reserved. 17 5.6 switch Multiple-Selection Statement • switch statement – Used for multiple selections
  • 18. © 2003 Prentice Hall, Inc. All rights reserved. Outline 18 SwitchTest.java Lines 16-21: Getting user’s input 1 // Fig. 5.9: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 import java.awt.Graphics; 4 5 import javax.swing.*; 6 7 public class SwitchTest extends JApplet { 8 int choice; // user's choice of which shape to draw 9 10 // initialize applet by obtaining user's choice 11 public void init() 12 { 13 String input; // user's input 14 15 // obtain user's choice 16 input = JOptionPane.showInputDialog( 17 "Enter 1 to draw linesn" + 18 "Enter 2 to draw rectanglesn" + 19 "Enter 3 to draw ovalsn" ); 20 21 choice = Integer.parseInt( input ); // convert input to int 22 23 } // end method init 24 25 // draw shapes on applet's background 26 public void paint( Graphics g ) 27 { 28 super.paint( g ); // call paint method inherited from JApplet 29 30 for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 31 Get user’s input in JApplet
  • 19. © 2003 Prentice Hall, Inc. All rights reserved. Outline 19 SwitchTest.java Line 32: controlling expression Line 32: switch statement Line 48 32 switch ( choice ) { // determine shape to draw 33 34 case 1: // draw a line 35 g.drawLine( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case 37 38 case 2: // draw a rectangle 39 g.drawRect( 10 + i * 10, 10 + i * 10, 40 50 + i * 10, 50 + i * 10 ); 41 break; // done processing case 42 43 case 3: // draw an oval 44 g.drawOval( 10 + i * 10, 10 + i * 10, 45 50 + i * 10, 50 + i * 10 ); 46 break; // done processing case 47 48 default: // draw string indicating invalid value entered 49 g.drawString( "Invalid value entered", 50 10, 20 + i * 15 ); 51 52 } // end switch 53 54 } // end for 55 56 } // end method paint 57 58 } // end class SwitchTest default case for invalid entries switch statement determines which case label to execute, depending on controlling expression user input (choice) is controlling expression
  • 20. © 2003 Prentice Hall, Inc. All rights reserved. Outline 20 SwitchTest.java
  • 21. © 2003 Prentice Hall, Inc. All rights reserved. Outline 21 SwitchTest.java
  • 22. © 2003 Prentice Hall, Inc. All rights reserved. 22 Fig. 5.10 switch multiple-selection statement activity diagram with break statements. case a action(s) break default action(s) [true] case b action(s) break case z action(s) break . . . [false] case a [true] [true] case b case z [false] [false]
  • 23. © 2003 Prentice Hall, Inc. All rights reserved. 23 5.7 break and continue Statements • break/continue – Alter flow of control • break statement – Causes immediate exit from control structure • Used in while, for, do…while or switch statements • continue statement – Skips remaining statements in loop body – Proceeds to next iteration • Used in while, for or do…while statements
  • 24. © 2003 Prentice Hall, Inc. All rights reserved. Outline 24 BreakTest.java Line 12 Lines 14-15 1 // Fig. 5.11: BreakTest.java 2 // Terminating a loop with break. 3 import javax.swing.JOptionPane; 4 5 public class BreakTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 int count; 11 12 for ( count = 1; count <= 10; count++ ) { // loop 10 times 13 14 if ( count == 5 ) // if count is 5, 15 break; // terminate loop 16 17 output += count + " "; 18 19 } // end for 20 21 output += "nBroke out of loop at count = " + count; 22 JOptionPane.showMessageDialog( null, output ); 23 24 System.exit( 0 ); // terminate application 25 26 } // end main 27 28 } // end class BreakTest Loop 10 times exit for structure (break) when count equals 5
  • 25. © 2003 Prentice Hall, Inc. All rights reserved. Outline 25 ContinueTest.ja va Line 11 Lines 13-14 1 // Fig. 5.12: ContinueTest.java 2 // Continuing with the next iteration of a loop. 3 import javax.swing.JOptionPane; 4 5 public class ContinueTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 11 for ( int count = 1; count <= 10; count++ ) { // loop 10 times 12 13 if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop 15 16 output += count + " "; 17 18 } // end for 19 20 output += "nUsed continue to skip printing 5"; 21 JOptionPane.showMessageDialog( null, output ); 22 23 System.exit( 0 ); // terminate application 24 25 } // end main 26 27 } // end class ContinueTest Loop 10 times Skip line 16 and proceed to line 11 when count equals 5
  • 26. © 2003 Prentice Hall, Inc. All rights reserved. 26 5.8 Labeled break and continue Statements • Labeled block – Set of statements enclosed by {} – Preceded by a label • Labeled break statement – Exit from nested control structures – Proceeds to end of specified labeled block • Labeled continue statement – Skips remaining statements in nested-loop body – Proceeds to beginning of specified labeled block
  • 27. © 2003 Prentice Hall, Inc. All rights reserved. Outline 27 BreakLabelTest. java Line 11 Line 14 Line 17 Lines 19-20 1 // Fig. 5.13: BreakLabelTest.java 2 // Labeled break statement. 3 import javax.swing.JOptionPane; 4 5 public class BreakLabelTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 11 stop: { // labeled block 12 13 // count 10 rows 14 for ( int row = 1; row <= 10; row++ ) { 15 16 // count 5 columns 17 for ( int column = 1; column <= 5 ; column++ ) { 18 19 if ( row == 5 ) // if row is 5, 20 break stop; // jump to end of stop block 21 22 output += "* "; 23 24 } // end inner for 25 26 output += "n"; 27 28 } // end outer for 29 Loop 10 times stop is the labeled block Exit to line 35 (next slide) Nested loop 5 times
  • 28. © 2003 Prentice Hall, Inc. All rights reserved. Outline 28 BreakLabelTest. java 30 // following line is skipped 31 output += "nLoops terminated normally"; 32 33 } // end labeled block 34 35 JOptionPane.showMessageDialog( null, output, 36 "Testing break with a label", 37 JOptionPane.INFORMATION_MESSAGE ); 38 39 System.exit( 0 ); // terminate application 40 41 } // end main 42 43 } // end class BreakLabelTest
  • 29. © 2003 Prentice Hall, Inc. All rights reserved. Outline 29 ContinueLabelTe st.java Line 11 Line 14 Line 17 Lines 21-22 1 // Fig. 5.14: ContinueLabelTest.java 2 // Labeled continue statement. 3 import javax.swing.JOptionPane; 4 5 public class ContinueLabelTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 11 nextRow: // target label of continue statement 12 13 // count 5 rows 14 for ( int row = 1; row <= 5; row++ ) { 15 output += "n"; 16 17 // count 10 columns per row 18 for ( int column = 1; column <= 10; column++ ) { 19 20 // if column greater than row, start next row 21 if ( column > row ) 22 continue nextRow; // next iteration of labeled loop 23 24 output += "* "; 25 26 } // end inner for 27 28 } // end outer for nextRow is the labeled block Loop 5 times Nested loop 10 times continue to line 11 (nextRow)
  • 30. © 2003 Prentice Hall, Inc. All rights reserved. Outline 30 ContinueLabelTe st.java 29 30 JOptionPane.showMessageDialog( null, output, 31 "Testing continue with a label", 32 JOptionPane.INFORMATION_MESSAGE ); 33 34 System.exit( 0 ); // terminate application 35 36 } // end main 37 38 } // end class ContinueLabelTest
  • 31. © 2003 Prentice Hall, Inc. All rights reserved. 31 5.9 Logical Operators • Logical operators – Allows for forming more complex conditions – Combines simple conditions • Java logical operators – && (conditional AND) – & (boolean logical AND) – || (conditional OR) – | (boolean logical inclusive OR) – ^ (boolean logical exclusive OR) – ! (logical NOT)
  • 32. © 2003 Prentice Hall, Inc. All rights reserved. 32 expression1 expression2 expression1 && expression2 false false false false true false true false false true true true Fig. 5.15 && (conditional AND) operator truth table. expression1 expression2 expression1 || expression2 false false false false true true true false true true true true Fig. 5.16 || (conditional OR) operator truth table.
  • 33. © 2003 Prentice Hall, Inc. All rights reserved. 33 expression1 expression2 expression1 ^ expression2 false false false false true true true false true true true false Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table. expression !expression false true true false Fig. 5.18 ! (logical negation, or logical NOT) operator truth table.
  • 34. © 2003 Prentice Hall, Inc. All rights reserved. Outline 34 LogicalOperator s.java Lines 16-20 Lines 23-27 1 // Fig. 5.19: LogicalOperators.java 2 // Logical operators. 3 import javax.swing.*; 4 5 public class LogicalOperators 6 7 public static void main( String args[] ) 8 { 9 // create JTextArea to display results 10 JTextArea outputArea = new JTextArea( 17, 20 ); 11 12 // attach JTextArea to a JScrollPane so user can scroll results 13 JScrollPane scroller = new JScrollPane( outputArea ); 14 15 // create truth table for && (conditional AND) operator 16 String output = "Logical AND (&&)" + 17 "nfalse && false: " + ( false && false ) + 18 "nfalse && true: " + ( false && true ) + 19 "ntrue && false: " + ( true && false ) + 20 "ntrue && true: " + ( true && true ); 21 22 // create truth table for || (conditional OR) operator 23 output += "nnLogical OR (||)" + 24 "nfalse || false: " + ( false || false ) + 25 "nfalse || true: " + ( false || true ) + 26 "ntrue || false: " + ( true || false ) + 27 "ntrue || true: " + ( true || true ); 28 Conditional AND truth table Conditional OR truth table
  • 35. © 2003 Prentice Hall, Inc. All rights reserved. Outline 35 LogicalOperator s.java Lines 30-34 Lines 37-41 Lines 44-48 Lines 51-53 29 // create truth table for & (boolean logical AND) operator 30 output += "nnBoolean logical AND (&)" + 31 "nfalse & false: " + ( false & false ) + 32 "nfalse & true: " + ( false & true ) + 33 "ntrue & false: " + ( true & false ) + 34 "ntrue & true: " + ( true & true ); 35 36 // create truth table for | (boolean logical inclusive OR) operator 37 output += "nnBoolean logical inclusive OR (|)" + 38 "nfalse | false: " + ( false | false ) + 39 "nfalse | true: " + ( false | true ) + 40 "ntrue | false: " + ( true | false ) + 41 "ntrue | true: " + ( true | true ); 42 43 // create truth table for ^ (boolean logical exclusive OR) operator 44 output += "nnBoolean logical exclusive OR (^)" + 45 "nfalse ^ false: " + ( false ^ false ) + 46 "nfalse ^ true: " + ( false ^ true ) + 47 "ntrue ^ false: " + ( true ^ false ) + 48 "ntrue ^ true: " + ( true ^ true ); 49 50 // create truth table for ! (logical negation) operator 51 output += "nnLogical NOT (!)" + 52 "n!false: " + ( !false ) + 53 "n!true: " + ( !true ); 54 55 outputArea.setText( output ); // place results in JTextArea 56 Logical NOT truth table Boolean logical exclusive OR truth table Boolean logical inclusive OR truth table Boolean logical AND truth table
  • 36. © 2003 Prentice Hall, Inc. All rights reserved. Outline 36 LogicalOperator s.java 57 JOptionPane.showMessageDialog( null, scroller, 58 "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); 59 60 System.exit( 0 ); // terminate application 61 62 } // end main 63 64 } // end class LogicalOperators
  • 37. © 2003 Prentice Hall, Inc. All rights reserved. 37 Operators Associativity Type ++ -- right to left unary postfix ++ -- + - ! (type) right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right conditional AND || left to right conditional OR ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 5.20 Precedence/associativity of the operators discussed so far.
  • 38. © 2003 Prentice Hall, Inc. All rights reserved. 38 5.10 Structured Programming Summary • Sequence structure – “built-in” to Java • Selection structure – if, if…else and switch • Repetition structure – while, do…while and for
  • 39. © 2003 Prentice Hall, Inc. All rights reserved. 39 Fig. 5.21 Java’s single-entry/single-exit sequence, selection and repetition statements. [t] [f] [f] [t] break break [t] break [t] [f] [t] [f] [t] [f] [t] [f] Repetition while statement do while statement for statement SelectionSequence if else statement (double selection) if statement (single selection) switch statement (multiple selection) . . . [t][f] default
  • 40. © 2003 Prentice Hall, Inc. All rights reserved. 40 Rules for Forming Structured Programs 1) Begin with the “simplest activity diagram” (Fig. 5.23). 2) Any action state can be replaced by two action states in sequence. 3) Any action state can be replaced by any control statement (sequence, if, if else, switch, while, do while or for). 4) Rules 2 and 3 can be applied as often as you like and in any order. Fig. 5.22 Rules for forming structured programs. action state Fig. 5.23 Simplest activity diagram.
  • 41. © 2003 Prentice Hall, Inc. All rights reserved. 41 Fig. 5.24 Repeatedly applying rule 2 of Fig. 5.22 to the simplest activity diagram. . . .action state action state apply Rule 2 apply Rule 2 apply Rule 2 action state action state action state action state action state action state
  • 42. © 2003 Prentice Hall, Inc. All rights reserved. 42 Fig. 5.25 Applying rule 3 of Fig. 5.22 to the simplest activity diagram. action state apply Rule 3 apply Rule 3 apply Rule 3 action stateaction state action stateaction state action stateaction state [f] [t] [f] [t] [f] [t][f] [t]
  • 43. © 2003 Prentice Hall, Inc. All rights reserved. 43 Fig. 5.26 Activity diagram with illegal syntax. action state action state action state action state
  • 44. © 2003 Prentice Hall, Inc. All rights reserved. 445.11 (Optional Case Study) Thinking About Objects: Identifying Objects’ States and Activities • State – Describes an object’s condition at a given time • Statechart diagram (UML) – Express how an object can change state – Express under what conditions an object can change state – Diagram notation (Fig. 5.28) • States are represented by rounded rectangles – e.g., “Not Pressed” and “Pressed” • Solid circle (with attached arrowhead) designates initial state • Arrows represent transitions (state changes) – Objects change state in response to messages • e.g., “buttonPressed” and “buttonReset”
  • 45. © 2003 Prentice Hall, Inc. All rights reserved. 45 Fig. 5.27 Statechart diagram for FloorButton and ElevatorButton objects. buttonReset buttonPressed PressedNot pressed
  • 46. © 2003 Prentice Hall, Inc. All rights reserved. 465.11 (Optional Case Study) Thinking About Objects: Identifying Objects’ States and Activities (cont.): • Activity diagram (UML) – Models an object’s workflow during program execution – Models the actions that an object will perform – Diagram notation (Fig. 5.28) • Activities are represented by ovals • Solid circle designates initial activity • Arrows represents transitions between activities • Small diamond represents branch – Next transition at branch is based on guard condition
  • 47. © 2003 Prentice Hall, Inc. All rights reserved. 47 Fig. 5.28 Activity diagram for a Person object. [floor door closed] press elevator button enter elevator move toward floor button wait for door to open press floor button wait for door to open [floor door open] exit elevator wait for passenger to exit elevator [passenger on elevator] [no passenger on elevator]
  • 48. © 2003 Prentice Hall, Inc. All rights reserved. 48 Fig. 5.29 Activity diagram for the Elevator object. close elevator door ring bell reset elevator button [elevator idle][button on destination floor pressed] open elevator door [elevator moving] [button on current floor pressed] [floor button pressed] [elevator button pressed] [summoned] [not summoned] set summoned to true set summoned to false move to destination floor [button on destination floor pressed] [button on current floor pressed]