Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Formulating Algorithms: Counter-Controlled Repetition - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Control Statements I

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Formulating Algorithms: Counter-Controlled Repetition - JavaScript(JS)

To illustrate how to develop algorithms, we solve several variations of a class-averaging problem.

Formulating Algorithms: Counter-Controlled Repetition

 

To illustrate how to develop algorithms, we solve several variations of a class-averaging problem. Consider the following problem statement:

 

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

 

The class average is equal to the sum of the grades divided by the number of students (10 in this case). The algorithm for solving this problem on a computer must input each of the grades, perform the averaging calculation and display the result.

 

Let us use pseudocode to list the actions to execute and specify the order in which the actions should execute. 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 executes. In this example, repetition terminates when the counter exceeds 10. In this section, we present a pseudocode algorithm (Fig. 7.6) and the corresponding program (Fig. 7.7). In the next section, we show how to develop pseudocode algorithms. Counter-controlled repetition often is 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 in which a script accumulates the sum of a series of values. A counter is a variable a script uses to count—in this case, to count the number of grades entered. Variables that store totals should normally be initialized to zero before they are used in a program.

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. 7.6 | Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

 

 

 

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 7.7: average.html -->

 

      <!-- Counter-controlled repetition to calculate a class average. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Class Average Program</title>

 

        <script type = "text/javascript">

        <!--

 

        var total; // sum of grades

 

        var gradeCounter; // number of grades entered

 

        var grade; // grade typed by user (as a string)

 

        var gradeValue; // grade value (converted to integer)

 

        var average; // average of all grades

        // Initialization Phase

 

        total = 0; // clear total

 

        gradeCounter = 1; // prepare to loop

 

        // Processing Phase

 

        while ( gradeCounter <= 10 ) // loop 10 times

{

 

// prompt for input and read grade from user

grade = window.prompt( "Enter integer grade:", "0" );

 

// convert grade from a string to an integer

gradeValue = parseInt( grade );

 

// add gradeValue to total

total = total + gradeValue;

// add 1 to gradeCounter

      gradeCounter = gradeCounter + 1;

 

      } // end while

      // Termination Phase

 

      average = total / 10; // calculate the average

 

      // display average of exam grades

 

      document.writeln(

      "<h1>Class average is " + average + "</h1>" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run the script again<p>

 

      </body>

 

</html>


Fig. 7.7 | Counter-controlled repetition to calculate a class average.

 

Lines 12–16 declare variables total, gradeCounter, grade, gradeValue, average.

 

The variable grade will store the string the user types into the prompt dialog. The variable gradeValue will store the integer value of the grade the user enters into the prompt dialog.

 

Lines 19–20 are assignment statements that initialize total to 0 and gradeCounter to 1. Note that variables total and gradeCounter are initialized before they are used in a calculation.

Line 23 indicates that the while statement continues iterating while the value of gradeCounter is less than or equal to 10. Line 27 corresponds to the pseudocode state-ment “Input the next grade.” The statement displays a prompt dialog with the prompt "Enter integer grade:" on the screen.

 

After the user enters the grade, line 30 converts it from a string to an integer. We must convert the string to an integer in this example; otherwise, the addition statement in line 33 will be a string-concatenation statement rather than a numeric sum.

 

Next, the program updates the total with the new gradeValue entered by the user. Line 33 adds gradeValue to the previous value of total and assigns the result to total. This statement seems a bit strange, because it does not follow the rules of algebra. Keep in mind that JavaScript operator precedence evaluates the addition (+) operation before the assignment (=) operation. The value of the expression on the right side of the assignment operator always replaces the value of the variable on the left side of the assignment operator.

 

The program now is ready to increment the variable gradeCounter to indicate that a grade has been processed and to read the next grade from the user. Line 36 adds 1 to gradeCounter, so the condition in the while statement will eventually become false and terminate the loop. After this statement executes, the program continues by testing the condition in the while statement in line 23. If the condition is still true, the statements in lines 27–36 repeat. Otherwise the program continues execution with the first statement in sequence after the body of the loop (i.e., line 40).

 

Line 40 assigns the results of the average calculation to variable average. Lines 43–44 write a line of XHTML text in the document that displays the string "Class average is " followed by the value of variable average as an <h1> element in the browser.

 

Execute the script in a web browser by double clicking the XHTML document (from Windows Explorer). This script parses any user input as an integer. In the sample program execution in Fig. 7.7, the sum of the values entered (100, 88, 93, 55, 68, 77, 83, 95, 73 and 62) is 794. Although the treats all input as integers, the averaging calculation in the program does not produce an integer. Rather, the calculation produces a floating-point number (i.e., a number containing a decimal point). The average of the 10 integers input by the user in this example is 79.4.

JavaScript actually represents all numbers as floating-point numbers in memory. Floating-point numbers often develop through division, as shown in this example. When we divide 10 by 3, the result is 3.3333333…, with the sequence of 3’s 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. Although floating-point numbers are not always 100 percent 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. The point here is that few applications require high- precision floating-point values, so calling this number simply 98.6 is fine for most appli-cations.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.