Archive for April, 2007

116 Control Structures: Part 1 Chapter 4 Line (Web hosting account)

Wednesday, April 25th, 2007

116 Control Structures: Part 1 Chapter 4 Line 47 displays the value of average. We specify average as the second argument to WriteLine. Method WriteLine will convert this argument to a string and display its value. 4.10 Formulating Algorithms with Top-Down, StepwiseRefinement: Case Study 3 (Nested Control Structures) Let us work through another complete problem. We will again formulate the algorithm using pseudocode and top-down, stepwise refinement; we will write a corresponding C# program. Consider the following problem statement: A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, several of the students who completed this course took the licensing examination. 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 the 10 students. Next to each name is written a 1 if the student passed the exam and a 2 if the student failed the exam. 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 of students who failed the exam. 4. If more than 8 students passed the exam, print the message Raise tuition. After reading the problem statement carefully, we make the following observations about the problem: 1. The program must process test results for 10 students. A counter-controlled loop will be used. 2. Each test result is a number either a 1 or a 2. Each time the program reads a test result, the program must determine if the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it is a 2. (An exercise at the end of the chapter considers the consequences of this assumption.) 3. Two counters keep track of the exam results one to count the number of students who passed the exam and one to count the number of students who failed. 4. After the program processes all the results, it must decide if more than eight students passed the exam. Let us proceed with top-down, stepwise refinement. We begin with a pseudocode representation of the top: Analyze exam results and decide if tuition should be raised Once again, it is important to emphasize that the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode can be evolved naturally into a C# program. Our first refinement is
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

Chapter 4 Control Structures: Part 1 115 cast (Web hosting account)

Wednesday, April 25th, 2007

Chapter 4 Control Structures: Part 1 115 cast operator to create this temporary value. Line 44 uses the cast operator ( double ) to create a temporary floating-point copy of its operand total. Using a cast operator in this manner is called explicit conversion. The value stored in total is still an integer. The calculation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. Note that the cast does not modify the value stored in memory for total. Rather it creates a temporary value that is used only for this calculation. Common Programming Error 4.7 Assuming that integer division rounds (rather than truncates) can lead to incorrect results. C# can evaluate only arithmetic expressions in which the data types of the operands are identical. To ensure that the operands are of the same type, C# performs implicit conversion (also called promotion) on selected operands. Through implicit conversion, in an expression containing the data types int and double, int operands are promoted to double. In our example, the temporary double version of total is divided by the int gradeCounter. Therefore, a temporary version of gradeCounter is promoted to double, the calculation is performed and the result of the floating-point division is assigned to average. Cast operators are available for most data types. The cast operator is known as a unary operator (i.e., an operator that takes only one operand) and is formed by placing parentheses around a data type name. In Chapter 3, Introduction to C# Programming, we studied the binary arithmetic operators. C# also supports unary versions of the plus (+) and minus (-) operators, so the programmer can write expressions like -7or +5. Cast operators associate from right to left and have the same precedence as other unary operators, such as unary + and unary -. This precedence is one level higher than that of the multiplicative operators *, / and % and one level lower than that of parentheses. (See the operator precedence chart in Appendix A.) In our precedence charts, we indicate the cast operator with the notation (type) to show that any type name can form a cast operator. Common Programming Error 4.8 Using floating-point numbers in a manner that assumes that they are precisely represented real numbers can lead to incorrect results. Real numbers are represented only approximately by computers. Good Programming Practice 4.7 Do not compare floating-point values for equality or inequality. Rather, test that the absolute value of the difference between two floating-point numbers is less than a specified small value. Despite the fact that floating-point numbers are not always 100% precise, they have numerous applications. For example, when we speak of a normal body temperature of 98.6, we do not need to be precise to a large number of digits. When we view the temperature on a thermometer and read it as 98.6, it may actually be 98.5999473210643. Calling such a number simply 98.6 is fine for most applications. Floating-point numbers also develop through division. When we divide 10 by 3, the result is 3.3333333 , with the sequence of 3s repeating infinitely. The computer allocates only a fixed amount of space to hold such a value, so the stored floating-point value can be only an approximation.
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

114 Control Structures: Part 1 Chapter 4 structure. (Windows 2003 server web)

Tuesday, April 24th, 2007

114 Control Structures: Part 1 Chapter 4 structure. This value is used to determine if the program s flow of control should enter the body of the while structure. If the while structure condition is false (i.e., the user has entered the sentinel value), the body of the while structure does not execute (i.e., no grades were entered). If, on the other hand, the condition is true, the body begins execution, and the value input by the user is processed (added to the total). Then, the next value is input from the user before the end of the while structure s body. When program control reaches the closing right brace (}) of the body (line 39), execution continues with the next test of the while structure condition. The new value input by the user determines if the while structure s body should execute again. Notice that the next value is input from the user immediately before the while structure condition is evaluated (line 37). This allows the program to determine whether the value just input by the user is the sentinel value before the program processes that value as a valid grade. If the value is the sentinel value, the while structure terminates, and the value is not added to the total. Notice the block that composes the while loop in Fig. 4.9. Without the braces, the last three statements in the body of the loop would be outside the loop, causing the computer to interpret the code incorrectly, as follows: while ( gradeValue != -1 ) // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; // prompt for input and read grade from user Console.Write( “Enter Integer Grade, -1 to Quit: ” ); gradeValue = Int32.Parse( Console.ReadLine() ); An infinite loop occurs in the program if the user fails to input the sentinel -1 as the input value at line 23 (before the while structure). Common Programming Error 4.6 Omitting the curly braces that delimit a block in a repetition structure can lead to logic errors, such as infinite loops. Good Programming Practice 4.6 In a sentinel-controlled loop, the prompts requesting data entry should remind the user of the sentinel value. Averages do not always evaluate to integer values. Often, an average is a value such as 3.333 or 2.7, that contains a fractional part. These values are floating-point numbers and usually are represented by the data type double. We declare the variable average as type double to capture the fractional result of our calculation. However, the result of the calculation total / gradeCounter is an integer because total and grade- Counter are both integer variables. Dividing two integers results in integer division, in which any fractional part of the calculation is truncated and the result is a whole number. The calculation is performed first, thus the fractional part is lost before the result is assigned to average. To produce a floating-point calculation with integer values, we must create temporary values that are floating-point numbers for the calculation. C# provides the unary
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision virtual web hosting services

Web server version - Chapter 4 Control Structures: Part 1 113 30

Tuesday, April 24th, 2007

Chapter 4 Control Structures: Part 1 113 30 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 34 // prompt for input and read grade from user 35 // convert grade from string to integer 36 Console.Write( “Enter Integer Grade, -1 to Quit: ” ); 37 gradeValue = Int32.Parse( Console.ReadLine() ); 38 39 } // end while 40 41 // termination phase 42 if ( gradeCounter != 0 ) 43 { 44 average = ( double ) total / gradeCounter; 45 46 // display average of exam grades 47 Console.WriteLine( “nClass average is {0}”, average ); 48 49 } 50 else 51 { 52 Console.WriteLine( “No grades were entered.” ); 53 } 54 55 } // end method Main 56 57 } // end class Average2 Enter Integer Grade, -1 to Quit: 97 Enter Integer Grade, -1 to Quit: 88 Enter Integer Grade, -1 to Quit: 72 Enter Integer Grade, -1 to Quit: -1 Class average is 85.6666666666667 Fig. 4.9 Class-average program with sentinel-controlled repetition. (Part 2 of 2.) In this example, we examine how control structures may be stacked on top of one another, in sequence. The while structure (lines 26 39) is followed immediately by an if structure (lines 42 51). Much of the code in this program is identical to the code in Fig. 4.7, so we concentrate on the new features in this example. Line 14 declares variable average to be of type double. This change allows us to store the result of the class-average calculation as a floating-point number. Line 18 initializes gradeCounterto 0 because no grades have been input yet recall that this program uses sentinel-controlled repetition. To keep an accurate record of the number of grades entered, variable gradeCounter is incremented only when a valid grade value is input. Notice the differences between sentinel-controlled repetition and the counter-controlled repetition of Fig. 4.7. In counter-controlled repetition, we read a value from the user during each pass of the while structure for the specified number of iterations. In sentinel- controlled repetition, we read one value (line 23) before the program reaches the while
Note: In case you are looking for affordable webhost to host and run your web application check Vision cheap hosting services

112 Control Structures: Part 1 Chapter 4 Software (Msn web hosting)

Monday, April 23rd, 2007

112 Control Structures: Part 1 Chapter 4 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 prints 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 convert the pseudocode to a C# program. Implementing the C# program then normally occurs in a straightforward manner. The C# program for this pseudocode is shown in Fig. 4.9. Notice from the output that each grade entered is an integer, although the averaging calculation is likely to produce a number with a decimal point. The type int cannot represent real numbers, so this program uses data type double to handle floating-point numbers. The program also introduces the cast operator (line 44) to handle the type conversion for the averaging calculation. These features are explained in detail in our discussion of Fig. 4.9. 1 // Fig. 4.9: Average2.cs 2 // Class average with sentinel-controlled repetition. 3 4 using System; 5 6 class Average2 7 { 8 static void Main( string[] args ) 9 { 10 int total, // sum of grades 11 gradeCounter, // number of grades entered 12 gradeValue; // grade value 13 14 double average; // average of all grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 0; // prepare to loop 19 20 // processing phase 21 // prompt for input and convert to integer 22 Console.Write( “Enter Integer Grade, -1 to Quit: ” ); 23 gradeValue = Int32.Parse( Console.ReadLine() ); 24 25 // loop until a -1 is entered by user 26 while ( gradeValue != -1 ) 27 { 28 // add gradeValue to total 29 total = total + gradeValue; Fig. 4.9 Class-average program with sentinel-controlled repetition. (Part 1 of 2.)
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision web design programs services

Chapter 4 Control Structures: Part 1 111 Note (Web server)

Monday, April 23rd, 2007

Chapter 4 Control Structures: Part 1 111 Note that a value is input both before reaching the loop and at the end of the loop s body. As we enter the loop, the value input before the loop is tested to determine whether it is the sentinel. If so, the loop terminates; otherwise, the body of the loop executes. The body processes the grade, then inputs the next grade. Then, the new grade is tested at the top of the loop to determine if that grade is the sentinel. 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 We test for the possibility of division by zero a logic error that, if undetected, causes 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.4 When performing division by an expression whose value could be zero, explicitly test for this case and handle it appropriately in your program, possibly printing an error message. Good Programming Practice 4.5 Include blank lines in pseudocode programs for increased readability. The blank lines separate pseudocode control structures and the program s phases. 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.
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

110 Control Structures: Part 1 Chapter 4 Determine (Web host)

Sunday, April 22nd, 2007

110 Control Structures: Part 1 Chapter 4 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 a complete representation of a program. Unfortunately, the top rarely conveys a sufficient amount of detail from which to write the C# algorithm. Therefore, we conduct the refinement process. We divide the top into a series of smaller tasks and list these in the order in which they must be performed. This results in the following first refinement: Initialize variables Input, sum up and count the quiz grades Calculate and print the class average Here, only the sequence structure has been used the steps listed are to be executed in order, one after the other. Software Engineering Observation 4.4 Each refinement, including the top, is a complete specification of the algorithm; only the level of detail in each refinement 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 numbers, a count of how many numbers have been processed, a variable to receive the value of each grade and a variable to hold the calculated average. The pseudocode statement Initialize variables 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 determined 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 are to be processed, thus we use sentinel-controlled repetition. The user types in legitimate grades one at a time. After the last legitimate grade is typed, 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 enters 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) 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 structure.
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

Chapter 4 Control Structures: Part 1 109 (Web hosting ratings) used

Sunday, April 22nd, 2007

Chapter 4 Control Structures: Part 1 109 used in a calculation. Recall that using uninitialized variables in calculations results in compilation errors. Line 20 indicates that the while structure should continue as long as the value of gradeCounter is less than or equal to 10. Lines 23 and 26 correspond to the pseudocode statement Input the next grade. The statement on line 23 displays the prompt Enter integergrade: on the screen. The statement on line 26 reads the information entered by the user, converts it to an int and stores the value in gradeValue. Next, line 29 updates the totalwith the new gradeValue by adding gradeValue to the previous value of total and assigning the result to total. The program is now ready to increment the variable gradeCounter to indicate that a grade has been processed. Line 32 adds 1 to gradeCounter, so the condition in the while structure eventually will become false and terminate the loop. Line 36 assigns the results of the average calculation to variable average. Line 39 displays a message containing the string “Classaverageis ” followed by the value of variable average. The averaging calculation produces an integer result. Actually, the sum of the grade- point values in this example is 794, which, when divided by 10, yields 79.4. Such numbers with a decimal point are called floating-point numbers; we discuss 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. 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 are to be 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 end of data entry. The user inputs all grades and then types the sentinel value to indicate that the last grade has been entered. Sentinel-controlled repetition often is called indefinite repetition because the number of repetitions is not known before the loop begins executing. The sentinel value cannot be confused with an acceptable input value. Grades on a quiz are normally nonnegative integers, thus -1 is an acceptable sentinel value for this problem. A run of the class-average program might process a stream of inputs such as 95, 96, 75, 74, 89 and -1. The program would then compute and print the class average for the grades 95, 96, 75, 74 and 89. The sentinel value, -1, should not enter into the averaging calculation. Common Programming Error 4.5 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, a problem known as an infinite loop. We approach the class-average program with top-down, stepwise refinement, a technique essential to the development of well-structured algorithms. We begin with a pseudocode representation of the top:
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

108 Control Structures: Part 1 Chapter 4 31 (Free php web host)

Saturday, April 21st, 2007

108 Control Structures: Part 1 Chapter 4 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 } 34 35 // termination phase 36 average = total / 10; // integer division 37 38 // display average of exam grades 39 Console.WriteLine( “nClass average is {0}”, average ); 40 41 } // end Main 42 43 } // end class Average1 Enter integer grade: 100 Enter integer grade: 88 Enter integer grade: 93 Enter integer grade: 55 Enter integer grade: 68 Enter integer grade: 77 Enter integer grade: 83 Enter integer grade: 95 Enter integer grade: 73 Enter integer grade: 62 Class average is 79 Fig. 4.7 Class average program with counter-controlled repetition. (Part 2 of 2.) Note the references in the algorithm (Fig. 4.6) to a total and a counter. The pseudocode variable total accumulates the sum of a series of values. A counter is a variable that counts in this case, that counts the number of grades entered. Variables that store totals normally should 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. Testing and Debugging Tip 4.3 Initialize counters and totals. Line 6 begins the definition of class Average1. Remember that an application class definition must contain a Main method (lines 8 41) to begin execution of the application. Lines 10 13 declare variables total, gradeCounter, gradeValue and average to be of type int. Variable gradeValue will store the value the user inputs after the value is converted from a string to an int. Good Programming Practice 4.4 Always place a blank line between a declaration and executable statements. This makes the declarations stand out in a program and contributes to program clarity. Lines 16 17 are assignment statements that initialize total to 0 and grade- Counter to 1. Variables total and gradeCounter are initialized before they are
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision servlet hosting services

Chapter 4 Control Structures: Part 1 107 (Web server type) Section

Saturday, April 21st, 2007

Chapter 4 Control Structures: Part 1 107 Section 4.9, we show how to develop a pseudocode algorithm. Counter-controlled repetition is also called definite repetition because the number of repetitions is known before the loop begins executing. 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. 1 // Fig. 4.7: Average1.cs 2 // Class average with counter-controlled repetition. 3 4 using System; 5 6 class Average1 7 { 8 static void Main( string[] args ) 9 { 10 int total, // sum of grades 11 gradeCounter, // number of grades entered 12 gradeValue, // grade value 13 average; // average of all grades 14 15 // initialization phase 16 total = 0; // clear total 17 gradeCounter = 1; // prepare to loop 18 19 // processing phase 20 while ( gradeCounter <= 10 ) // loop 10 times 21 { 22 // prompt for input and read grade from user 23 Console.Write( "Enter integer grade: " ); 24 25 // read input and convert to integer 26 gradeValue = Int32.Parse( Console.ReadLine() ); 27 28 // add gradeValue to total 29 total = total + gradeValue; 30 Fig. 4.7 Class average program with counter-controlled repetition. (Part 1 of 2.)
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision php5 hosting services