Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Examples Using the for Statement - JavaScript(JS)

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

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

Examples Using the for Statement - JavaScript(JS)

The examples in this section show methods of varying the control variable in a for state-ment.

Examples Using the for Statement

 

The examples in this section show methods of varying the control variable in a for state-ment. In each case, we write the appropriate for header. Note the change in the relational operator for loops that decrement the control variable.

 

a) Vary the control variable from 1 to 100 in increments of 1.

 

for ( var i = 1; i <= 100; ++i )

 

b) Vary the control variable from 100 to 1 in increments of -1 (i.e., decrements of 1).

 

for ( var i = 100; i >= 1; --i )

 

c) Vary the control variable from 7 to 77 in steps of 7.

 

for ( var i = 7; i <= 77; i += 7 )

 

d) Vary the control variable from 20 to 2 in steps of -2.

 

for ( var i = 20; i >= 2; i -= 2 )

 

e) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17, 20.

 

for ( var j = 2; j <= 20; j += 3 )

 

        Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0.

 

for ( var j = 99; j >= 0; j -= 11 )

 

The next two scripts demonstrate the for repetition statement. Figure 8.5 uses the for statement to sum the even integers from 2 to 100. Note that the increment expression adds 2 to the control variable number after the body executes during each iteration of the loop. The loop terminates when number has the value 102 (which is not added to the sum).

 

      <?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. 8.5: Sum.html -->

 

      <!-- Summation with the for repetition structure. -->

 

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

 

      <head>

 

      <title>Sum the Even Integers from 2 to 100</title>

 

        <script type = "text/javascript">

        <!--

var sum = 0;

for ( var number = 2; number <= 100; number += 2 )

sum += number;

document.writeln( "The sum of the even integers " +

      "from 2 to 100 is " + sum );

      // -->

 

      </script>

 

      </head><body></body>

 

</html>


Fig. 8.5 | Summation with the for repetition structure.

Note that the body of the for statement in Fig. 8.5 actually could be merged into the rightmost (increment) portion of the for header by using a comma, as follows:

 

for ( var number = 2; number <= 100; sum += number, number += 2);

 

Similarly, the initialization sum = 0 could be merged into the initialization section of the for statement.

The next example computes compound interest (compounded yearly) using the for statement. Consider the following problem statement:

 

A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts:

 

a = p (1 + r) n

where

 

p is the original amount invested (i.e., the principal) r is the annual interest rate

 

n is the number of years

a is the amount on deposit at the end of the nth year.

This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit. Figure 8.6 presents the solution to this problem, displaying the results in a table.

 

Lines 16–18 declare three variables and initialize principal to 1000.0 and rate to .05. Lines 20–21 write an XHTML <table> tag, and lines 22–23 write the caption that summarizes the table’s content. Lines 24–25 create the table’s header section (<thead>), a

    <?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. 8.6: Interest.html -->

 

    <!-- Compound interest calculation with a for loop. -->

 

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

 

    <head>

 

    <title>Calculating Compound Interest</title>

 

      <style type = "text/css">

 

      table { width: 100% }

th           { text-align: left }

 

      </style>

 

      <script type = "text/javascript">

      <!--

 

      var amount; // current amount of money

 

      var principal = 1000.0; // principal amount

 

      var rate = .05; // interest rate

              document.writeln(

 

      "<table border = \"1\">" ); // begin the table

 

      document.writeln(

      "<caption>Calculating Compound Interest</caption>" );

 

      document.writeln(

      "<thead><tr><th>Year</th>" ); // year column heading

 

      document.writeln(

      "<th>Amount on deposit</th>" ); // amount column heading

 

      document.writeln( "</tr></thead><tbody>" );

      // output a table row for each year

 

      for ( var year = 1; year <= 10; ++year )

{

amount = principal * Math.pow( 1.0 + rate, year );

document.writeln( "<tr><td>" + year +

"</td><td>" + amount.toFixed(2) +

"</td></tr>" );

} //end for

      document.writeln( "</tbody></table>" );

      // -->

 

      </script>

 

      </head><body></body>

 

</html>


Fig. 8.6 | Compound interest calculation with a for loop.

 

row (<tr>) and a column heading (<th>) containing “Year.” Lines 26–28 create a table

 

heading for “Amount on deposit” and write the closing </tr> and </thead> tags.

 

The for statement (lines 31–37) executes its body 10 times, incrementing control variable year from 1 to 10 (note that year represents n in the problem statement). Java-Script does not include an exponentiation operator. Instead, we use the Math object’s pow method for this purpose. Math.pow(x, y) calculates the value of x raised to the yth power. Method Math.pow takes two numbers as arguments and returns the result.

 

Line 33 performs the calculation using the formula given in the problem statement. Lines 34–36 write a line of XHTML markup that creates another row in the table. The first column is the current year value. The second column displays the value of amount. Line 39 writes the closing </tbody> and </table> tags after the loop terminates.

 

Line 35 introduces the Number object and its toFixed method. The variable amount contains a numerical value, so JavaScript represents it as a Number object. The toFixed method of a Number object formats the value by rounding it to the specified number of decimal places. On line 35, amount.toFixed(2) outputs the value of amount with two decimal places.

 

Variables amount, principal and rate represent numbers in this script. Remember that JavaScript represents all numbers as floating-point numbers. This feature is conve-nient in this example, because we are dealing with fractional parts of dollars and need a type that allows decimal points in its values.

unfortunately, floating-point numbers can cause trouble. Here is a simple example of what can go wrong when using floating-point numbers to represent dollar amounts (assuming that dollar amounts are displayed with two digits to the right of the decimal point): Two dollar amounts stored in the machine could be 14.234 (which would nor-mally be rounded to 14.23 for display purposes) and 18.673 (which would normally be rounded to 18.67 for display purposes). When these amounts are added, they produce the internal sum 32.907, which would normally be rounded to 32.91 for display purposes. Thus your printout could appear as


but a person adding the individual numbers as printed would expect the sum to be 32.90. You have been warned!

 

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


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