Thursday, 18 December 2014

// The "Exercise44C_Chapter4" class.
// (from the Carter book)

// Exercise 4.4 - Question 3 (a & b):

// Write a FOR statement that has the form of the FOR statement
// in Example 2 (empty body) and that performs the indicated action.
// (NOTE:  Execute 3(a) separately from 3(b) --> use // to comment
// out the part that you don't want to run.)

import java.awt.*;
import hsa.Console;

public class Exercise44C_Chapter4
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        // Question 3 (a):

        // Calculate 'sum' before incrementing 'i' and 'j'
        // using an empty-body FOR statement, then display 'sum'
        // after the FOR statement is complete.  NOTE:  Use a
        // cast to make sure that the calculation is converted to double

        double sum = 0;
        for (int i = 1, j = 2 ; i <= 19 & j <= 20 ; sum += (double) i / j,
                i++, j++)
            ;
        c.println ("sum of the terms i/j is: " + sum);
        c.println ();

        // Question 3 (b):

        // Calculate 'total' before incrementing 'i' and 'j'
        // using an empty-body FOR statement, then display 'total'
        // after the FOR statement is complete.  NOTE: Display
        // 'total' IN the FOR statement to make sure the calculation
        // is occurring

        // int total = 0;
        // for (int i = 1, j = 100; i <= 50 & j >= 2; total += i*j,
        //                                            c.println (total),
        //                                            i++, j -= 2)
        //     ;
        // c.println("total of i * j is: " + total);

    } // main method
} // Exercise44C_Chapter4 class

No comments:

Post a Comment