Click Refresh (or Reload) to run the script again
Here, the <script> block is located at the bottom of the XHTML markup to allow it to be rendered by the browser before the JS code executes. The <div> section above with id of output is used to display the results using the DOM approach.
The program prompts the user to submit a series of grades which can be floating points or integers. The user indicates that input is complete by entering -1. (This is the sentinel technique for while loops.) If you look closely at the code it will actually accept any value less than zero as the sentinel. This is due to the nature of how numbers are represented by the computer. It usually doesn't work to test for equality to terminate a loop when using floats.
The grades are 'remembered' for display at the end by concatenating them to a string variable as they are entered adding a space to separate them. The program keeps a running total of both the sum of the grades as they are entered as well as the number of grades entered and calculates and displays the average when input has completed.
var intGradeCounter, // number of grades entered
floatGradeValue, // grade value
floatTotal, // sum of grades
floatAverage, // floatAverage of all grades
strGrade; // grade entered by user at prompt
var strGradeDisplay = ""; // Remember all the grades so you can display them
var DOMOut = document.getElementById("output"); // get handle to output
div
// Initialization phase
floatTotal = 0; // clear Total
intGradeCounter = 0; // clear the counter
// Processing phase
// prompt for input and read grade from user as string
strGrade = window.prompt("Enter Integer Grade, -1 to Quit:", "0" );
// convert grade from a String to a float
floatGradeValue = parseFloat( strGrade );
while ( floatGradeValue > -1 ) {
// add the new grade value to the Total
floatTotal += floatGradeValue;
// Remember the grades that were submitted by concatenating them
with spaces between
// so we can read them
strGradeDisplay += strGrade + " ";
// increment grade counter since we added a grade
intGradeCounter++; // same as intGradeCounter =
intGradeCounter + 1;
// prompt for input and read more grades from user until they finish
strGrade = window.prompt("Enter Integer Grade, -1 to Quit:", "0" );
// convert grade from a String to an float
floatGradeValue = parseFloat( strGrade );
}
// Termination phase
if ( intGradeCounter != 0 ) {
floatAverage = floatTotal / intGradeCounter;
// display Average of grades and their values
DOMOut.innerHTML = "<h1>Grades Average is " + floatAverage + </h1>" +
"<h2>Grade List: " + strGradeDisplay + "</h2>" +
"<h3>Click Refresh (or Reload) to run the script again.</h3>";
}
else
DOMOut.innerHTML = "<h1>No grades were entered</h1>" +
"<h2>Click Refresh (or Reload) to run the script again</h2>";