Thursday, 18 December 2014

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

// Exercise 4.3 - Question 6:

// Using a FOR loop.
// 6 (a) Write a program that will print a table containing the integers
//       from 1 to 40 along with their squares, square roots, and reciprocals.
//       (The table will look like a grid.)
// 6 (b) Modify your program from 6 (a) so that it inserts a blank line
//       after every fifth line of the table.  Use the modulus operator (%)
//       to do this.

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

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

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

        // Question 6 (a):

        // heading line comes before the FOR loop:
        c.println ("n\tsquare\tsqr.root\t\treciprocal");
        c.println ();

        // try this with one line of output first:
        // for (int n = 1; n <= 1; n++)
        // {
        // then, try it with 40 lines of output:
        // for (int n = 1; n <= 40; n++)
        // {
        //     // use 1 line of output for each 'n' value:
        //     c.print (n + "\t");
        //     c.print (n*n + "\t");
        //     c.print (Math.sqrt(n) + "\t\t");
        //     c.println (1/n);
        // }

        // Question 6 (b):

        for (int m = 1 ; m <= 40 ; m++)
        {
            // use 1 line of output for each 'n' value:
            c.print (m + "\t");
            c.print (m * m + "\t");
            c.print (Math.sqrt (m) + "\t\t");
            c.println (1 / m);
            // add this part for 6 (b):
            if (m % 5 == 0)
            {
                c.println ();
            }
        }

    } // main method
} // Exercise43E_Chapter4 class

No comments:

Post a Comment