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

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

Leave a Reply