Object Oriented Programming in java Dana F Doghramachi
Object Oriented Programming in java Dana F. Doghramachi Chapter -2 Control Structures 2015
Pseudocode • Pseudocode is an informal language that helps you develop algorithms without having to worry about the strict details of Java language syntax. • Particularly useful for developing algorithms that will be converted to structured portions of Java programs. • Helps you “think out” a program before attempting to write it in a programming language, such as Java. • You can type pseudocode conveniently, using any text-editor program. • Carefully prepared pseudocode can easily be converted to a corresponding Java program. • Pseudocode normally describes only statements representing the actions that occur after you convert a program from pseudocode to Java and the program is run on a computer. § e. g. , input, output or calculations. Chapter -2 - Control Structures 1
Control Structures • Sequential execution: Statements in a program execute one after the other in the order in which they are written. • Transfer of control: Various Java statements, enable you to specify that the next statement to execute is not necessarily the next one in sequence. • Bohm and Jacopini § Demonstrated that programs could be written without any goto statements. § All programs can be written in terms of only three control structures—the sequence structure, the selection structure (three types) and the repetition structure (three types). Chapter -2 - Control Structures 2
Control Structures (Cont. ) • Sequence structure § Built into Java. § The computer executes Java statements one after the other in the order in which they’re written. § The activity diagram in Fig. 2. 1 illustrates a typical sequence structure in which two calculations are performed in order. § Java lets you have as many actions as you want in a sequence structure. Chapter -2 - Control Structures 3
Fig. 2. 1 | Sequence structure activity diagram Chapter -2 - Control Structures 4
Control Structures (Cont. ) • Three types of selection statements. • if statement: § Performs an action, if a condition is true; skips it, if false. § Single-selection statement—selects or ignores a single action (or group of actions). • if…else statement: § Performs an action if a condition is true and performs a different action if the condition is false. § Double-selection statement—selects between two different actions (or groups of actions). • switch statement § Performs one of several actions, based on the value of an expression. § Multiple-selection statement—selects among many different actions (or groups of actions). Chapter -2 - Control Structures 5
Control Structures (Cont. ) • Three repetition statements (also called looping statements) § Perform statements repeatedly while a loop-continuation condition remains true. • while and for statements perform the action(s) in their bodies zero or more times § if the loop-continuation condition is initially false, the body will not execute. • The do…while statement performs the action(s) in its body one or more times. • if, else, switch, while, do and for are keywords. Chapter -2 - Control Structures 6
if Single-Selection Statement • Pseudocode If student’s grade is greater than or equal to 60 Print “Passed” • If the condition is false, the Print statement is ignored, and the next pseudocode statement in order is performed. • The preceding pseudocode If in Java: • if ( student. Grade >= 60 ) System. out. println( "Passed" ); • Can model each control statement as an activity diagram. Chapter -2 - Control Structures 7
Fig. 2. 2 | Sequence structure activity diagram Chapter -2 - Control Structures 8
if…else Double-Selection Statement • if…else double-selection statement—specify an action to perform when the condition is true and a different action when the condition is false. • Pseudocode If student’s grade is greater than or equal to 60 Print “Passed” Else Print “Failed” • The preceding If…Else pseudocode statement in Java: if ( grade >= 60 ) System. out. println( "Passed" ); else System. out. println( "Failed" ); • Figure 2. 3 illustrates the flow of control in the if…else statement. Chapter -2 - Control Structures 9
Fig. 2. 3 | if…else double-selection statement UML activity diagram Chapter -2 - Control Structures 10
if…else Double-Selection Statement (Cont. ) • • Conditional operator (? : )—shorthand if…else. Ternary operator (takes three operands) Operands and ? : form a conditional expression Operand to the left of the ? is a boolean expression—evaluates to a boolean value (true or false) • Second operand (between the ? and : ) is the value if the boolean expression is true • Third operand (to the right of the : ) is the value if the boolean expression evaluates to false. • Example: System. out. println( student. Grade >= 60 ? "Passed" : "Failed" ); • Evaluates to the string "Passed" if the boolean expression student. Grade >= 60 is true and to the string "Failed" if it is false. Chapter -2 - Control Structures 11
if…else Double-Selection Statement (Cont. ) • Can test multiple cases by placing if…else statements inside other if…else statements to create nested if…else statements. • Pseudocode: If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” Chapter -2 - Control Structures 12
if…else Double-Selection Statement (Cont. ) • This pseudocode may be written in Java as if ( student. Grade >= 90 ) System. out. println( "A" ); else if ( student. Grade >= 80 ) System. out. println( "B" ); else if ( student. Grade >= 70 ) System. out. println( "C" ); else if ( student. Grade >= 60 ) System. out. println( "D" ); else System. out. println( "F" ); • If student. Grade >= 90, the first four conditions will be true, but only the statement in the if part of the first if…else statement will execute. After that, the else part of the “outermost” if…else statement is skipped. Chapter -2 - Control Structures 13
if…else Double-Selection Statement (Cont. ) • Most Java programmers prefer to write the preceding nested if…else statement as if ( student. Grade >= 90 ) System. out. println( "A" ); else if ( student. Grade >= 80 ) System. out. println( "B" ); else if ( student. Grade >= 70 ) System. out. println( "C" ); else if ( student. Grade >= 60 ) System. out. println( "D" ); else System. out. println( "F" ); • The two forms are identical except for the spacing and indentation, which the compiler ignores. Chapter -2 - Control Structures 14
if…else Double-Selection Statement (Cont. ) • The if statement normally expects only one statement in its body. • To include several statements in the body of an if (or the body of an else for an if…else statement), enclose the statements in braces. • Statements contained in a pair of braces form a block. • Example: 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. "); } Chapter -2 - Control Structures 15
if…else Double-Selection Statement (Cont. ) • A logic error (e. g. , when both braces in a block are left out of the program) has its effect at execution time. • A fatal logic error causes a program to fail and terminate prematurely. • A nonfatal logic error allows a program to continue executing but causes it to produce incorrect results. • Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have an empty statement. • The empty statement is represented by placing a semicolon (; ) where a statement would normally be. Chapter -2 - Control Structures 16
while Repetition Statement • Repetition statement—repeats an action while a condition remains true. • Pseudocode While there are more items on my shopping list Purchase next item and cross it off my list • The repetition statement’s body may be a single statement or a block. • Eventually, the condition will become false. At this point, the repetition terminates, and the first statement after the repetition statement executes. Chapter -2 - Control Structures 17
while Repetition Statement (Cont. ) • Example of Java’s while repetition statement: find the first power of 3 larger than 100. Assume int variable product is initialized to 3. while ( product <= 100 ) product = 3 * product; • Each iteration 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. • Repetition terminates. The final value of product is 243. • Program execution continues with the next statement after the while statement. Chapter -2 - Control Structures 18
Example of Nested Control Statements • Home Work 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’ve been asked to write a program to summarize the results. You’ve been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed. Chapter -2 - Control Structures 19
Formulating Algorithms: Nested Control Statements (Cont. ) • Your program should analyze the results of the exam as follows: § 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. § Count the number of test results of each type. § Display a summary of the test results, indicating the number of students who passed and the number who failed. § If more than eight students passed the exam, print the message “Bonus to instructor!” Chapter -2 - Control Structures 20
Compound Assignment Operators • Statements like variable = variable operator expression; where operator is one of the binary operators +, -, *, / or % can be written in the form: variable operator= expression; • Example: c = c + 3; can be written with the addition compound assignment operator, +=, as c += 3; Fig. 2. 4 | Arithmetic compound assignment operators Chapter -2 - Control Structures 21
Increment and Decrement Operators • Unary increment operator, ++, adds one to its operand • Unary decrement operator, --, subtracts one from its operand Fig. 2. 5 | Increment and decrement operators Chapter -2 - Control Structures 22
Chapter -2 - Control Structures 23
Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires § a control variable (or loop counter) § the initial value of the control variable § the increment (or decrement) by which the control variable is modified each time through the loop (also known as each iteration of the loop) § the loop-continuation condition that determines if looping should continue. Chapter -2 - Control Structures 24
Chapter -2 - Control Structures 25
for Repetition Statement • for repetition statement § Specifies the counter-controlled-repetition details in a single line of code. Chapter -2 - Control Structures 26
for Repetition Statement (Cont. ) • When the for statement begins executing, the control variable is declared and initialized. • Next, the program checks the loop-continuation condition, which is between the two required semicolons. • If the condition initially is true, the body statement executes. • After executing the loop’s body, the program increments the control variable in the increment expression, which appears to the right of the second semicolon. • Then the loop-continuation test is performed again to determine whether the program should continue with the next iteration of the loop. • A common logic error with counter-controlled repetition is an off-by-one error. Chapter -2 - Control Structures 27
Fig. 2. 6 | for statement header components Chapter -2 - Control Structures 28
for Repetition Statement (Cont. ) • In most cases, the for statement can be represented with an equivalent while statement as follows: initialization; while ( loop. Continuation. Condition ) { statement increment; } • Typically, for statements are used for counter-controlled repetition and while statements for sentinel-controlled repetition. Chapter -2 - Control Structures 29
for Repetition Statement (Cont. ) • The initialization, loop-continuation condition and increment can contain arithmetic expressions. • For example, assume that x = 2 and y = 10. If x and y are not modified in the body of the loop, the statement for (int j = x; j <= 4 * x * y; j += y / x) • is equivalent to the statement for (int j = 2; j <= 80; j += 5) • The increment of a for statement may be negative, in which case it’s a decrement, and the loop counts downward. Chapter -2 - Control Structures 30
Chapter -2 - Control Structures 31
do…while Repetition Statement • The do…while repetition statement is similar to the while statement. • In the while, the program tests the loop-continuation condition at the beginning of the loop, before executing the loop’s body; if the condition is false, the body never executes. • The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. • When a do…while statement terminates, execution continues with the next statement in sequence. Chapter -2 - Control Structures 32
Chapter -2 - Control Structures 33
do…while Repetition Statement (Cont. ) • Braces are not required in the do…while repetition statement if there’s only one statement in the body. • Most programmers include the braces, to avoid confusion between the while and do…while statements. • Thus, the do…while statement with one body statement is usually written as follows: do { statement } while ( condition ); Chapter -2 - Control Structures 34
switch Multiple-Selection Statement • switch multiple-selection statement performs different actions based on the possible values of a constant integral expression of type byte, short, int or char. Chapter -2 - Control Structures 35
switch Multiple-Selection Statement (Cont. ) • The switch statement consists of a block that contains a sequence of case labels and an optional default case. • The program evaluates the controlling expression in the parentheses following keyword switch. • The program compares the controlling expression’s value (which must evaluate to an integral value of type byte, char, short or int) with each case label. • If a match occurs, the program executes that case’s statements. Chapter -2 - Control Structures 36
switch Multiple-Selection Statement (Cont. ) • switch does not provide a mechanism for testing ranges of values—every value must be listed in a separate case label. • Note that each case can have multiple statements. • switch differs from other control statements in that it does not require braces around multiple statements in a case. • Without break, the statements for a matching case and subsequent cases execute until a break or the end of the switch is encountered. This is called “falling through. ” • If no match occurs between the controlling expression’s value and a case label, the default case executes. • If no match occurs and there is no default case, program control simply continues with the first statement after the switch. Chapter -2 - Control Structures 37
switch Multiple-Selection Statement (Cont. ) • When using the switch statement, remember that each case must contain a constant integral expression. • An integer constant is simply an integer value. • In addition, you can use character constants—specific characters in single quotes, such as 'A', '7' or '$'— which represent the integer values of characters. • The expression in each case can also be a constant variable—a variable that contains a value which does not change for the entire program. Such a variable is declared with keyword final. Chapter -2 - Control Structures 38
switch Multiple-Selection Statement (Cont. ) • As of Java SE 8, you can use Strings in a switch statement’s controlling expression and in case labels as in: • switch( city ) { case "Maynard": zip. Code = "01754"; break; case "Marlborough": zip. Code = "01752"; break; case "Framingham": zip. Code = "01701"; break; } // end switch • Chapter -2 - Control Structures 39
break and continue Statements • The break statement, when executed in a while, for, do…while or switch, causes immediate exit from that statement. • Execution continues with the first statement after the control statement. • Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch. Chapter -2 - Control Structures 40
Chapter -2 - Control Structures 41
break and continue Statements (Cont. ) • The continue statement, when executed in a while, for or do…while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. • In while and do…while statements, the program evaluates the loop-continuation test immediately after the continue statement executes. • In a for statement, the increment expression executes, then the program evaluates the loopcontinuation test. Chapter -2 - Control Structures 42
Chapter -2 - Control Structures 43
- Slides: 44