Archive for September, 2007

168 Control Structures: Part 1 Chapter 4 Initialize (Hp web site)

Sunday, September 30th, 2007

168 Control Structures: Part 1 Chapter 4 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.8Pseudocode algorithm that uses sentinel-controlled repetition to solve Fig. the class-average problem. Software Engineering Observation 4.5 Many algorithms can be divided logically into three phases: an initialization phase that initializes the program variables; a processing phase that inputs data values and adjusts program variables accordingly and a termination phase that calculates and displays the results. The pseudocode algorithm in Fig. 4.8 solves the more general class-averaging problem. This algorithm was developed after only two levels of refinement. Sometimes more levels are necessary. Software Engineering Observation 4.6 The programmer terminates the top-down, stepwise refinement process when the pseudocode algorithm is specified in sufficient detail for the programmer to be able to convert the pseudocode to a Java applet or application. Normally, implementing the Java applet or application is then straightforward. The Java application and a sample execution are shown in Fig. 4.9. Although each grade is an integer, the averaging calculation is likely to produce a number with a decimal point (i.e., a real number). The type intcannot represent real numbers (i.e., numbers with decimal points), so this program uses data type double to handle floating-point numbers. The program introduces a special operator called a cast operator to handle the type conversion we will need for the averaging calculation. These features are explained in detail in the discussion of the application. In this example, we see that control structures may be stacked on top of one another (in sequence) just as a child stacks building blocks. The while structure (lines 33 47) is followed by an if/elsestructure (lines 52 63) in sequence. Much of the code in this program is identical to the code in Fig. 4.7, so we concentrate in this example on the new features and issues. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Crystaltech web hosting - Chapter 4 Control Structures: Part 1 167 may

Saturday, September 29th, 2007

Chapter 4 Control Structures: Part 1 167 may be refined as follows: Initialize total to zero Initialize counter to zero Notice that only the variables total and counter are initialized before they are used; the variables average and grade (for the calculated average and the user input, respectively) need not be initialized, because their values are replaced as they are calculated or input. The pseudocode statement Input, sum up and count the quiz grades requires a repetition structure (i.e., a loop) that successively inputs each grade. We do not know how many grades the user will input, so the program will use sentinel-controlled repetition. The user at the keyboard inputs legitimate grades one at a time. After inputting the last legitimate grade, the user types the sentinel value. The program tests for the sentinel value after each grade is input and terminates the loop when the user inputs the sentinel value. The second refinement of the preceding pseudocode statement is then 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) Notice that in pseudocode, we do not use braces around the pseudocode that forms the body of the while structure. We simply indent the pseudocode under the while, to show that it belongs to the while. Again, pseudocode is only an informal program development aid. The pseudocode statement Calculate and print the class average may be refined as follows: 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 Notice that we are testing for the possibility of division by zero a logic error that, if undetected, would cause the program to produce invalid output. The complete second refinement of the pseudocode algorithm for the class-average problem is shown in Fig. 4.8. Testing and Debugging Tip 4.1 When performing division by an expression whose value could be zero, explicitly test for this case and handle it appropriately in your program (such as by printing an error message) rather than allowing the division by zero to occur. Good Programming Practice 4.9 Include completely blank lines in pseudocode programs to make the pseudocode more readable. The blank lines separate pseudocode control structures, as well as the phases of the programs. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

166 Control Structures: Part 1 Chapter 4 In (Web hosting service)

Saturday, September 29th, 2007

166 Control Structures: Part 1 Chapter 4 In the first class-average example, the number of grades (10) was known in advance. In this example, no indication is given of how many grades the user will input. The program must process an arbitrary number of grades. How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average? One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate the end of data entry. The user types grades in until all legitimate grades have been entered. The user then types the sentinel value to indicate that the last grade has been entered. Sentinel-controlled repetition is often called indefinite repetition, because the number of repetitions is not known before the loop begins executing. Clearly, the sentinel value must be chosen so that it cannot be confused with an acceptable input value. Because grades on a quiz are normally nonnegative integers, 1 is an acceptable sentinel value for this problem. Thus, an execution of the class-average program might process a stream of inputs such as 95, 96, 75, 74, 89 and 1. In this case, the program would compute and print the class average for the grades 95, 96, 75, 74 and 89. ( 1 is the sentinel value, so it should not enter into the averaging calculation.) Common Programming Error 4.7 Choosing a sentinel value that is also a legitimate data value results in a logic error and may prevent a sentinel-controlled loop from terminating properly. We approach the class-average program with a technique called top-down, stepwise refinement, a method that is essential to the development of well-structured algorithms. We begin with a pseudocode representation of the top: Determine the class average for the quiz The top is a single statement that conveys the overall function of the program. As such, the top is, in effect, a complete representation of a program. Unfortunately, the top rarely conveys a sufficient amount of detail from which to write the Java algorithm. So we now begin the refinement process. We divide the top into a series of smaller tasks and list these tasks in the order in which they need to be performed. This procedure results in the following first refinement: Initialize variables Input, sum up and count the quiz grades Calculate and print the class average This pseudocode uses only the sequence structure the steps listed occur in order, one after the other. Software Engineering Observation 4.4 Each refinement, as well as the top itself, is a complete specification of the algorithm; only the level of detail varies. To proceed to the next level of refinement (i.e., the second refinement), we commit to specific variables. We need a running total of the grades, a count of how many grades have been processed, a variable to receive the value of each grade as it is input and a variable to store the calculated average. The pseudocode statement Initialize variables Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 4 Control Structures: Part 1 165 ceding (Com web hosting)

Friday, September 28th, 2007

Chapter 4 Control Structures: Part 1 165 ceding statement. The pseudocode statement Input the next grade requires the programmer to implement the process of obtaining the value from the user and converting it to a type that can be used in calculating the average. As you learn to program, you will find that you require fewer pseudocode statements to help you implement a program. Next, the program updates the total with the new gradeValue entered by the user. Line 33, total = total + gradeValue; adds gradeValue to the previous value of total and assigns the result to total. Line 36, gradeCounter = gradeCounter + 1; adds 1to gradeCounter to indicate that the program hasprocessed a grade and is ready to input the next grade from the user. Incrementing gradeCounter is necessary for the condition in the while structure to become false eventually and terminate the loop. Line 41, average = total / 10; // perform integer division assigns the results of the average calculation to variable average. Lines 44 46, JOptionPane.showMessageDialog( null, “Class average is ” + average, “Class Average”, JOptionPane.INFORMATION_MESSAGE ); display an information message dialog containing the string “Classaverageis ” followed by the value of variable average. The string ClassAverage (the third argument) is the title of the message dialog. Line 48, System.exit( 0 ); // terminate the program terminates the application. After compiling the class definition with javac, execute the application from the command window with the command java Average1 This command executes the Java interpreter and tells it that the main method for this application is defined in class Average1. Note that the averaging calculation in the program produced an integer result. Actually, the sum of the grade-point values in this example is 794, which, when divided by 10, should yield 79.4 (i.e., a number with a decimal point). We will see how to deal with such numbers (called floating-point numbers) in the next section. 4.9 Formulating Algorithms with Top-Down, StepwiseRefinement: Case Study 2 (Sentinel-Controlled Repetition) Let us generalize the class-average problem. Consider the following problem: Develop a class-averaging program that processes an arbitrary number of grades each time the program executes. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Anonymous web server - 164 Control Structures: Part 1 Chapter 4 user

Friday, September 28th, 2007

164 Control Structures: Part 1 Chapter 4 user types in the input dialog. Variable gradeValue stores the integer value of grade after the program converts it from a String to an int. Notice that the preceding declarations appear in the body of method main. Remember that variables declared in a method definition s body are local variables and can be used only from the line of their declaration in the method to the closing right brace (}) of the method definition. A local variable s declaration must appear before the variable is used in that method. A local variable declared in one method of a class cannot be accessed directly by other methods of a class. Good Programming Practice 4.7 Always place a blank line before a declaration that appears between executable statements. This format makes the declarations stand out in the program and contributes to program clarity. Good Programming Practice 4.8 If you prefer to place declarations at the beginning of a method, separate the declarations from the executable statements in that method with one blank line, to highlight where the declarations end and the executable statements begin. Common Programming Error 4.6 Attempting to use a local variable s value before initializing the variable (normally with an assignment statement) results in a compile error indicating that the variable may not have been initialized. The value of a local variable cannot be used until the variable is initialized. The program will not compile properly until the variable receives an initial value. Lines 19 20, total = 0; // clear total gradeCounter = 1; // prepare to loop are assignment statements that initialize totalto 0 and gradeCounterto 1. Note that these statements initialize variables total and gradeCounter before they are used in calculations. Line 23, while ( gradeCounter <= 10 ) { // loop 10 times indicates that the while structure should continue looping (also called iterating) as long as the value of gradeCounter is less than or equal to 10. Lines 26 27, grade = JOptionPane.showInputDialog( “Enter integer grade: ” ); correspond to the pseudocode statement Input the next grade. The statement displays an input dialog with the prompt Enterintegergrade: on the screen. After the user enters the grade, the program converts it from a String to an intat line 30, gradeValue = Integer.parseInt( grade ); Remember that class Integer is from package java.lang that the compiler imports in every Java program. The pseudocode for the class-average problem does not reflect the pre Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 4 Control Structures: Part (Web site domain) 1 163 Fig.

Thursday, September 27th, 2007

Chapter 4 Control Structures: Part 1 163 Fig. 4.7Class-average program with counter-controlled repetition (part 3 of 3). Fig. 4. Good Programming Practice 4.6 Initialize counters and totals. Line 5, import javax.swing.JOptionPane; imports class JOptionPane to enable the program to read data from the keyboard and output data to the screen using the input dialog and message dialog shown in Chapter 2. Line 7 begins the definition of application class Average1. Remember that the definition of an application class must contain a main method (lines 10 49) in order for the application to be executed. Lines 12 16, int total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average; // average of all grades String grade; // grade typed by user declare variables total, gradeCounter, gradeValue and average to be of type intand variable gradeto be of type String. Variable gradestores the Stringthe Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Zeus web server - 162 Control Structures: Part 1 Chapter 4 18

Wednesday, September 26th, 2007

162 Control Structures: Part 1 Chapter 4 18 // Initialization Phase 19 total = 0; // clear total 20 gradeCounter = 1; // prepare to loop 21 22 // Processing Phase 23 while ( gradeCounter <= 10 ) { // loop 10 times 24 25 // prompt for input and read grade from user 26 grade = JOptionPane.showInputDialog( 27 “Enter integer grade: ” ); 28 29 // convert grade from a String to an integer 30 gradeValue = Integer.parseInt( grade ); 31 32 // add gradeValue to total 33 total = total + gradeValue; 34 35 // add 1 to gradeCounter 36 gradeCounter = gradeCounter + 1; 37 38 } // end while structure 39 40 // Termination Phase 41 average = total / 10; // perform integer division 42 43 // display average of exam grades 44 JOptionPane.showMessageDialog( null, 45 “Class average is ” + average, “Class Average”, 46 JOptionPane.INFORMATION_MESSAGE ); 47 48 System.exit( 0 ); // terminate the program 49 50 } // end method main 51 52 } // end class Average1 Fig. 4.7Class-average program with counter-controlled repetition (part 2 of 3). Fig. 4. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 4 Control Structures: Part 1 161 Let (Web site)

Tuesday, September 25th, 2007

Chapter 4 Control Structures: Part 1 161 Let us use pseudocode to list the actions to be executed and specify the order in which these actions should be executed. We use counter-controlled repetition to input the grades one at a time. This technique uses a variable called a counter to control the number of times a set of statements will execute. In this example, repetition terminates when the counter exceeds 10. In this section, we present a pseudocode algorithm (Fig. 4.6) and the corresponding program (Fig. 4.7) to solve this probem using counter-controlled repetition. In the next section, we show how pseudocode algorithms are developed. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing. Note the references in the algorithm to a total and a counter. A total is a variable used to accumulate the sum of a series of values. A counter is a variable used to count in this case, to count the number of grades entered. Variables used to store totals should normally be initialized to zero before being used in a program; otherwise, the sum would include the previous value stored in the total s memory location. 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.6Pseudocode algorithm that uses counter-controlled repetition to solve Fig. the class-average problem. 1 // Fig. 4.7: Average1.java 2 // Class average program with counter-controlled repetition. 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class Average1 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 int total, // sum of grades input by user 13 gradeCounter, // number of grades entered 14 gradeValue, // grade value 15 average; // average of all grades 16 String grade; // grade typed by user 17 Fig. 4.7Class-average program with counter-controlled repetition (part 1 of 3). Fig. 4. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Fedora web server - 158 Control Structures: Part 1 Chapter 4 To

Tuesday, September 18th, 2007

158 Control Structures: Part 1 Chapter 4 To force the preceding nested if structure to execute as it was originally intended, the structure must be written as follows: if ( x > 5 ) { if ( y > 5 ) System.out.println( “x and y are > 5″ ); } else System.out.println( “x is <= 5" ); The braces ({}) indicate to the compiler that the second ifstructure is in the body of the first if structure and that the else is matched with the first if structure. In Exercise 4.21 and Exercise 4.22, you will investigate the dangling-else problem further. The if selection structure normally expects only one statement in its body. To include several statements in the body of an if structure, enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. Software Engineering Observation 4.2 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 structure: 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 gradeis less than 60, the program executes both statements in the body of the else and prints Failed. You must take this course again. Notice the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement System.out.println( “You must take this course again.” ); would be outside the body of the elsepart of the if structure and would execute regardless of whether the grade is less than 60. Common Programming Error 4.2 Forgetting one or both of the braces that delimit a block can lead to syntax or logic errors. Syntax errors (such as when one brace in a block is left out of the program) are caught by the compiler. A logic error (such as 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 the program produces incorrect results. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Unlimited web hosting - Chapter 4 Control Structures: Part 1 157 If

Tuesday, September 18th, 2007

Chapter 4 Control Structures: Part 1 157 If studentGrade is greater than or equal to 90, the first four conditions will be true, but only the System.out.println statement after the first test will be executed. After that particular System.out.println is executed, the else part of the outer if/else statement is skipped. Good Programming Practice 4.4 If there are several levels of indentation, each level should be indented by the same additional amount of space. Most Java programmers prefer to write the preceding if structure as if ( grade >= 90 ) System.out.println( “A” ); else if ( grade >= 80 ) System.out.println( “B” ); else if ( grade >= 70 ) System.out.println( “C” ); else if ( grade >= 60 ) System.out.println( “D” ); else System.out.println( “F” ); Both forms are equivalent. The latter form is popular because it avoids the deep indentation of the code to the right. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability. It is important to note that the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). This attribute 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" ); appears to indicate that if x is greater than 5, the if structure in its body determines if y is also greater than 5. If so, the string "xandyare>5″ is output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else structure outputs the string “xis<=5". Beware! The preceding nested if structure does not execute as it would appear to. The compiler actually interprets the preceding structure as if ( x > 5 ) if ( y > 5 ) System.out.println( “x and y are > 5″ ); else System.out.println( “x is <= 5" ); in which the body of the first if structure is an if/else structure. This structure tests if x is greater than 5. If so, execution continues by testing if y is also greater than 5. If the second condition is true, the proper string "xandyare>5″ is displayed. However, if the second condition is false, the string “xis<=5″is displayed, even though we know that x is greater than 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01