Advertisement
RokiAdhytama

Average 2 - Chapter 8

Jul 2nd, 2022
948
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.80 KB | None
  1. <html xmlns = "http://www.w3.org/1999/xhtml">
  2.    <head>
  3.       <title>Class Average Program:
  4.           Sentinel-controlled Repetition</title>
  5.  
  6.       <script type = "text/javascript">
  7.          <!--
  8.          var gradeCounter,  // number of grades entered
  9.              gradeValue,    // grade value
  10.              total,         // sum of grades
  11.              average,       // average of all grades
  12.              grade;         // grade typed by user
  13.  
  14.          // Initialization phase
  15.          total = 0;         // clear total
  16.          gradeCounter = 0;  // prepare to loop
  17.      
  18.          // Processing phase
  19.          // prompt for input and read grade from user
  20.          grade = window.prompt(
  21.               "Enter Integer Grade, -1 to Quit:", "0" );
  22.  
  23.          // convert grade from a String to an integer
  24.          gradeValue = parseInt( grade );
  25.  
  26.          while ( gradeValue != -1 ) {
  27.             // add gradeValue to total
  28.             total = total + gradeValue;
  29.  
  30.             // add 1 to gradeCounter
  31.             gradeCounter = gradeCounter + 1;
  32.  
  33.             // prompt for input and read grade from user
  34.             grade = window.prompt(
  35.                  "Enter Integer Grade, -1 to Quit:", "0" );
  36.  
  37.             // convert grade from a String to an integer
  38.             gradeValue = parseInt( grade );
  39.          }
  40.  
  41.          // Termination phase
  42.          if ( gradeCounter != 0 ) {
  43.             average = total / gradeCounter;  
  44.  
  45.             // display average of exam grades
  46.             document.writeln(
  47.                "<h1>Class average is " + average + "</h1>" );
  48.          }
  49.          else
  50.             document.writeln( "<p>No grades were entered</p>" );
  51.          // -->
  52.       </script>
  53.    </head>
  54.  
  55.    <body>
  56.       <p>Click Refresh (or Reload) to run the script again</p>
  57.    </body>
  58. </html>
Advertisement
RAW Paste Data Copied
Advertisement