BTCOE 404 ObjectOriented Programming using Java UNITIII Control
BT-COE 404 Object-Oriented Programming using Java • • UNIT-III Control Statements: Algorithms, Pseudocode, Control Structures, if Single. Selection Statement, if. . . else Double-Selection Statement, while Repetition Statement, Formulating Algorithms: Counter-Controlled Repetition, Formulating Algorithms: Sentinel-Controlled Repetition, Formulating Algorithms: Nested Control Statements, Compound Assignment Operators, Increment and Decrement Operators, Primitive Types, Essentials of Counter-Controlled Repetition, for Repetition Statement, Examples Using for Statement, do. . . while Repetition Statement, switch Multiple-Selection Statement, break and continue Statements, Logical Operators.
Control Structures
3 Introduction • We learn about Control Structures – Structured-programming principle – Control structures help build and manipulate objects 2002 Prentice Hall. All rights reserved.
4 Algorithms • Algorithm – Series of actions in specific order • The actions executed • The order in which actions execute • Program control – Specifying the order in which actions execute • Control structures help specify this order 2002 Prentice Hall. All rights reserved.
5 Pseudocode • Pseudocode – Informal language for developing algorithms – Not executed on computers – Helps developers “think out” algorithms 2002 Prentice Hall. All rights reserved.
Control Structures • Sequential execution – Program statements execute one after the other • Transfer of control – Three control statements can specify order of statements • Sequence structure - the computer executes Java statements one after the other in the order in which they are written—that is, in sequence. • Selection structure - The if statement is a single-selection statement because it selects or ignores a single action (or, as we will soon see, a single group of actions). The if…else statement is called a double-selection statement because it selects between two different actions (or groups of actions). The switch statement is called a multiple-selection statement because it selects among many different actions (or groups of actions). 2002 Prentice Hall. All rights reserved. 6
• Repetition structure - Java provides three repetition statements (also called looping statements) that enable programs to perform statements repeatedly as long as a condition (called the loop-continuation condition) remains true. - The repetition statements are the while, do…while and for statements. - The while and for statements perform the action (or group of actions) in their bodies zero or more times— if the loop-continuation condition is initially false, the action (or group of actions) will not execute. - The do…while statement performs the action (or group of actions) in its body one or more times. - words if, else, switch, while, do and for are Java keywords. 2002 Prentice Hall. All rights reserved.
8 Flowlines Action Symbols add grade to total = total + grade; add 1 to counter = counter + 1; Connector Symbols Fig 4. 1 Flowcharting Java’s sequence structure. 2002 Prentice Hall. All rights reserved.
9 2002 Prentice Hall. All rights reserved.
10 Selection Structures • Java has a sequence structure “built-in” • Java provides three selection structures – if/else – switch • Java provides three repetition structures – while – do/while – do • Each of these words is a Java keyword 2002 Prentice Hall. All rights reserved.
The if Selection Structure • Single-entry/single-exit structure • Perform action only when condition is true • Action/decision programming model • If student’s grade is greater than or equal to 60 Print “Passed” • if ( student. Grade >= 60 ) System. out. println( "Passed" ); 2002 Prentice Hall. All rights reserved. 11
12 Decision Symbol grade >= 60 true print “Passed” false Fig 4. 3 Flowcharting the single-selection if structure. 2002 Prentice Hall. All rights reserved.
The if/else Selection Structure • • • Perform action only when condition is true Perform different specified action when condition is false Conditional operator (? : ) : System. out. println( student. Grade >= 60 ? "Passed" : "Failed" ); Nested if/else selection structures pseudocode statement If student’s grade is greater than or equal to 60 Print “Passed” Else Print “Failed” • Java Code if ( grade >= 60 ) System. out. println( "Passed" ); else System. out. println( "Failed" ); 2002 Prentice Hall. All rights reserved. 13
14 false true grade >= 60 print “Failed” print “Passed” Fig 4. 4 Flowcharting the double-selection if/else structure. 2002 Prentice Hall. All rights reserved.
Nested if…else Statements • A program can test multiple cases by placing if…else statements inside other if…else statements to create nested if…else statements. • For example, the following pseudocode represents a nested if…else that prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades: • 2002 Prentice Hall. All rights reserved. 15
Dangling-else Problem 16 • The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what is referred to as the dangling-else problem. • For example, if ( x > 5 ) if ( y > 5 ) System. out. println( "x and y are > 5" ); else System. out. println( "x is <= 5" ); • indicate that if x is greater than 5, the nested if statement determines whether y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears that if x is not greater than 5, the else part of the if…else outputs the string "x is <= 5". • The compiler actually interprets the statement as- The outer if statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the secondition is true, the proper string —"x and y are > 5"—is displayed. However, if the secondition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5. 2002 Prentice Hall. All rights reserved.
17 Blocks • The if statement normally expects only one statement in its body. To include several statements in the body of an if enclose the statements in braces ({ and }). • A set of statements contained within a pair of braces is called a block. A block can be placed anywhere in a program that a single statement can be placed. • The following example includes a block in the else-part of an if…else statement: if ( grade >= 60 ) System. out. println( "Passed" ); else { System. out. println( "Failed" ); System. out. println( "You must take this course again. " ); } • In this case, if grade is less than 60, the program executes both statements in the body of the else and prints Failed. You must take this course again. 2002 Prentice Hall. All rights reserved.
4. 7 The while Repetition Structure 18 • Repeat action while condition remains true • A repetition statement (also called a looping statement or a loop) allows the programmer to specify that a program should repeat an action while some condition remains true. • The pseudocode statement While there are more items on my shopping list Purchase next item and cross it off my list • Code: int product = 3; while ( product <= 100 ) product = 3 * product; • When this while statement begins execution, the value of variable product is 3. Each iteration of the while statement multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively. When variable product becomes 243, the while statement condition—product <= 100—becomes false. This terminates the repetition, so the final value of product is 243. At this point, program execution continues with the next statement after the while statement. 2002 Prentice Hall. All rights reserved.
19 true product <= 100 product = 3 * product false Fig 4. 5 Flowcharting the while repetition structure. 2002 Prentice Hall. All rights reserved.
4. 8 Formulating Algorithms: Case Study 1 (Counter. Controlled Repetition) • Counter – Variable that controls number of times set of statements executes • Average 1. java calculates grade averages – uses counters to control repetition 2002 Prentice Hall. All rights reserved. 20
21 Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 4. 6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem. 2002 Prentice Hall. All rights reserved.
22 2002 Prentice Hall. All rights reserved.
23 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Outline // Fig. 4. 7: Average 1. java // Class average program with counter-controlled repetition. // Java extension packages import javax. swing. JOption. Pane; Declare variables; grade. Counter is the counter public class Average 1 { // main method begins execution of Java application public static void main( String args[] ) { int total, // sum of grades input by user grade. Counter, // number of grades entered Continue looping as long as grade. Value, // grade value grade. Counter is less than or average; // average of all grades equal to 10 String grade; // grade typed by user // Initialization Phase total = 0; // clear total grade. Counter = 1; // prepare to loop // Processing Phase while ( grade. Counter <= 10 ) { // loop 10 times Average 1. java grade. Counter Line 23 // prompt for input and read grade from user grade = JOption. Pane. show. Input. Dialog( "Enter integer grade: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( grade ); // add grade. Value to total = total + grade. Value; 2002 Prentice Hall. All rights reserved. 24
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // add 1 to grade. Counter = grade. Counter + 1; } // end while structure // Termination Phase average = total / 10; // perform integer division Outline Average 1. java // display average of exam grades JOption. Pane. show. Message. Dialog( null, "Class average is " + average, "Class Average", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate the program } // end method main } // end class Average 1 2002 Prentice Hall. All rights reserved. 25
Outline Average 1. java 2002 Prentice Hall. All rights reserved. 26
Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) • Sentinel value(signal value/ dummy value /flag value) – Used to indicated the end of data entry – Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing. • Average 2. java has indefinite repetition - problem: Develop a class-averaging program that processes grades for an arbitrary number of students each time it is run. – User enters sentinel value (-1) to end repetition top-down, stepwise refinement - essential to the development of well-structured programs. • top—a single statement that conveys the overall function of the program: Determine the class average for the quiz • first refinement: Initialize variables Input, sum and count the quiz grades Calculate and print the class average 2002 Prentice Hall. All rights reserved. 27
28 Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Fig. 4. 8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem. 2002 Prentice Hall. All rights reserved.
29 2002 Prentice Hall. All rights reserved.
30 2002 Prentice Hall. All rights reserved.
31 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Fig. 4. 9: Average 2. java // Class average program with sentinel-controlled repetition. // Java core packages import java. text. Decimal. Format; Outline Average 2. java // Java extension packages import javax. swing. JOption. Pane; public class Average 2 { // main method begins execution of Java application public static void main( String args[] ) { int grade. Counter, // number of grades entered grade. Value, // grade value total; // sum of grades double average; // average of all grades String input; // grade typed by user // Initialization phase total = 0; // clear total grade. Counter = 0; // prepare to loop // Processing phase // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( input ); 2002 Prentice Hall. All rights reserved. 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Outline while ( grade. Value != -1 ) { // add grade. Value to total = total + grade. Value; loop until grade. Counter equals sentinel value (-1) // add 1 to grade. Counter = grade. Counter + 1; // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( input ); } Average 2. java Line 33 Line 50 Format numbers to nearest hundredth // Termination phase Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); if ( grade. Counter != 0 ) { average = (double) total / grade. Counter; // display average of exam grades JOption. Pane. show. Message. Dialog( null, "Class average is " + two. Digits. format( average ), "Class Average" , JOption. Pane. INFORMATION_MESSAGE ); } else JOption. Pane. show. Message. Dialog( null, "No grades were entered" , "Class Average", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate application 2002 Prentice Hall. All rights reserved. 33
67 } // end method main 68 69 } // end class Average 2 Outline Average 2. java 2002 Prentice Hall. All rights reserved. 34
Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) • Nested control structures • Consider the following problem statement: A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, ten of the students who completed this course took the exam. The college wants to know how well its students did on the exam. You have been asked to write a program to summarize the results. You have been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or 2 if the student failed. Your program should analyze the results of the exam as follows: 1. Input each test result (i. e. , a 1 or a 2). Display the message “Enter result” on the screen each time the program requests another test result. 2. Count the number of test results of each type. 3. Display a summary of the test results indicating the number of students who passed and the number who failed. 4. If more than eight students passed the exam, print the message “Raise tuition. ” 2002 Prentice Hall. All rights reserved. 35
36 Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig. Pseudocode for examination-results problem. 2002 Prentice Hall. All rights reserved.
37 2002 Prentice Hall. All rights reserved.
38 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Outline // Fig. 4. 11: Analysis. java // Analysis of examination results. // Java extension packages import javax. swing. JOption. Pane; public class Analysis { Loop until student counter is greater than 10 // main method begins execution of Java application public static void main( String args[] ) { // initializing variables in declarations int passes = 0, // number of passes failures = 0, // number of failures student = 1, // student counter result; // one exam result String input, // user-entered value output; // output string // process 10 students; counter-controlled loop while ( student <= 10 ) { Analysis. java Line 21 Line 31 Nested control structure // obtain result from user input = JOption. Pane. show. Input. Dialog( "Enter result (1=pass, 2=fail)" ); // convert result to int result = Integer. parse. Int( input ); // process result if ( result == 1 ) passes = passes + 1; else failures = failures + 1; 2002 Prentice Hall. All rights reserved. 39
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 student = student + 1; } // termination phase output = "Passed: " + passes + "n. Failed: " + failures; Outline Analysis. java if ( passes > 8 ) output = output + "n. Raise Tuition"; JOption. Pane. show. Message. Dialog( null, output, "Analysis of Examination Results", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate application } // end method main } // end class Analysis 2002 Prentice Hall. All rights reserved. 40
41 4. 11 Assignment Operators • Assignment Operators – Abbreviate assignment expressions – Any statement of form • variable = variable operator expression; – Can be written as • variable operator= expression; – e. g. , addition assignment operator += • c = c + 3 – can be written as • c += 3 2002 Prentice Hall. All rights reserved.
42 2002 Prentice Hall. All rights reserved.
43 4. 12 Increment and Decrement Operators • Unary increment operator (++) – Increment variable’s value by 1 • Unary decrement operator (--) – Decrement variable’s value by 1 • Preincrement / predecrement operator • Post-increment / post-decrement operator 2002 Prentice Hall. All rights reserved.
2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 4. 14: Increment. java // Preincrementing and postincrementing public class Increment { Outline Line 13 postincrements c // main method begins execution of Java application public static void main( String args[] ) { int c; c = 5; Line 20 preincrements System. out. println( c ); // print 5 System. out. println( c++ ); // print 5 then postincrement System. out. println( c ); // print 6 Increment. java Line 13 postincrement c Line 20 preincrement System. out. println(); // skip a line c = 5; System. out. println( c ); // print 5 System. out. println( ++c ); // preincrement then print 6 System. out. println( c ); // print 6 } // end method main } // end class Increment 5 5 6 6 2002 Prentice Hall. All rights reserved.
46 2002 Prentice Hall. All rights reserved.
47 4. 13 Primitive Data Types • Primitive types – “building blocks” for more complicated types • Java is strongly typed – All variables in a Java program must have a type • Java primitive types – portable across computer platforms that support Java 2002 Prentice Hall. All rights reserved.
48 2002 Prentice Hall. All rights reserved.
49 5. 2 Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires: – Name of control variable (loop counter) – Initial value of control variable – Increment/decrement of control variable through each loop – Condition that tests for control variable’s final value 2002 Prentice Hall. All rights reserved.
50 2002 Prentice Hall. All rights reserved.
51 5. 3 The for Repetition Structure • Handles counter-controlled-repetition details 2002 Prentice Hall. All rights reserved.
2002 Prentice Hall. All rights reserved.
Outline Line 20 for keyword Control variable name Final value of control variable for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Increment of control variable Loop-continuation condition Fig. 5. 3 Components of a typical for structure header. 2002 Prentice Hall. All rights reserved. 53
54 5. 3 The for Repetition Structure (cont. ) for ( expression 1; expression 2; expression 3 ) statement; can usually be rewritten as: expression 1; while ( expression 2 ) { statement; expression 3; } 2002 Prentice Hall. All rights reserved.
55 Fig. Flowcharting a typical for repetition structure. 2002 Prentice Hall. All rights reserved.
56 5. 4 Examples Using the for Structure • Varying control variable in for structure – 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 decrements of – 1 • for ( int i = 100; i >= 1; i-- ) – Vary control variable from 7 to 77 in steps of 7 • for ( int i = 7; i <= 77; i += 7 ) 2002 Prentice Hall. All rights reserved.
Application: Summing the Even Integers from 2 to 20 2002 Prentice Hall. All rights reserved. 57
Application: Compound-Interest Calculations • A person invests $1000 in a savings account yielding 5% interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts: a = p (1 + r)n where p is the original amount invested (i. e. , the principal) r is the annual interest rate (e. g. , use 0. 05 for 5%) n is the number of years a is the amount on deposit at the end of the nth year. 2002 Prentice Hall. All rights reserved. 58
59 2002 Prentice Hall. All rights reserved.
60 5. 5 The switch Multiple-Selection Structure • switch structure – Used for multiple selections – Java provides the switch multiple-selection statement to perform different actions based on the possible values of an integer variable or expression. Each action is associated with the value of a constant integral expression (i. e. , a constant value of type byte, short, int or char, but not long) that the variable or expression on which the switch is based may assume. 2002 Prentice Hall. All rights reserved.
2002 Prentice Hall. All rights reserved.
2002 Prentice Hall. All rights reserved.
63 2002 Prentice Hall. All rights reserved.
64 2002 Prentice Hall. All rights reserved.
65 2002 Prentice Hall. All rights reserved.
66 The do/while Repetition Structure • do/while structure – Similar to while structure – Tests loop-continuation after performing body of loop • i. e. , loop body always executes at least once 2002 Prentice Hall. All rights reserved.
67 2002 Prentice Hall. All rights reserved.
68 2002 Prentice Hall. All rights reserved.
69 5. 7 Statements break and continue • 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 2002 Prentice Hall. All rights reserved.
70 2002 Prentice Hall. All rights reserved.
71 2002 Prentice Hall. All rights reserved.
72 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 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 5. 13: Break. Label. Test. java // Using the break statement with a label // Java extension packages import javax. swing. JOption. Pane; stop is the labeled block public class Break. Label. Test { Break. Label. Test. java Line 14 // main method begins execution of Java application public static void main( String args[] ) { String output = ""; Line 17 Loop 10 times stop: { // labeled block Nested loop 5 times // count 10 rows for ( int row = 1; row <= 10; row++ ) { Line 20 Lines 23 -24 // count 5 columns for ( int column = 1; column <= 5 ; column++ ) { // if row is 5, jump to end of "stop" block if ( row == 5 ) break stop; // jump to end of stop block output += "* "; } // end inner for structure output += "n"; Exit to line 37 (next slide) } // end outer for structure // the following line is skipped output += "n. Loops terminated normally" ; 2002 Prentice Hall. All rights reserved. 73
36 37 38 39 40 41 42 43 44 45 46 47 } // end labeled block JOption. Pane. show. Message. Dialog( null, output, "Testing break with a label" , JOption. Pane. INFORMATION_MESSAGE ); Outline Break. Label. Test. java System. exit( 0 ); // terminate application } // end method main } // end class Break. Label. Test 2002 Prentice Hall. All rights reserved. 74
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Outline // Fig. 5. 14: Continue. Label. Test. java // Using the continue statement with a label // Java extension packages import javax. swing. JOption. Pane; next. Row is the labeled block Continue. Label. Test. jav a public class Continue. Label. Test { // main method begins execution of Java application public static void main( String args[] ) { Loop String output = ""; Line 14 Line 17 5 times Line 21 next. Row: // target label of continue statement // count 5 rows Nested loop for ( int row = 1; row <= 5; row++ ) { output += "n"; // count 10 columns per row for ( int column = 1; column <= 10; column++ ) { // if column greater than row, start next row if ( column > row ) continue next. Row; // next iteration of // labeled loop output += "* "; 10 times Lines 24 -25 } // end inner for structure } // end outer for structure 75 continue to line 14 (next. Row) 2002 Prentice Hall. All rights reserved.
34 35 36 37 38 39 40 41 42 JOption. Pane. show. Message. Dialog( null, output, "Testing continue with a label" , JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate application Outline 76 Continue. Label. Test. jav a } // end method main } // end class Continue. Label. Test 2002 Prentice Hall. All rights reserved.
77 5. 9 Logical Operators • Logical operators – Allows forming more complex conditions – Combines simple conditions • Java logical operators – – – && & || | ^ ! (logical AND) (boolean logical AND) (logical OR) (boolean logical inclusive OR) (boolean logical exclusive OR) (logical NOT) 2002 Prentice Hall. All rights reserved.
78 2002 Prentice Hall. All rights reserved.
79 2002 Prentice Hall. All rights reserved.
80 2002 Prentice Hall. All rights reserved.
81 2002 Prentice Hall. All rights reserved.
82 2002 Prentice Hall. All rights reserved.
83 2002 Prentice Hall. All rights reserved.
84 2002 Prentice Hall. All rights reserved.
85 2002 Prentice Hall. All rights reserved.
89 The nesting rule 2002 Prentice Hall. All rights reserved.
- Slides: 95