Thursday, 18 December 2014

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

// Example 10 - Chapter 2

// Finds a pendulum's period (in seconds) depending on the force of
// gravity and the given length of the pendulum.

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

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

    public static void main (String[] args)
    {
        c = new Console ();
        final double G = 9.8;   // acceleration due to gravity in m**2

        c.println ("Give the pendulum a length in metres");
        double length = c.readDouble ();

        // find the period, rounded to nearest tenth of a second
        // (depends on length and the force of gravity)
        double period = 2 * Math.PI * Math.sqrt (length / G);
        // round the period value up and then show it as a double
        period = Math.round (10 * period) / 10.0;

        c.println ("For a length of " + length + " m,"
                + " the pendulum's period is " + period + " seconds.");

    } // main method
} // Pendulum class

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

// Exercise 4.5 - Question 4 (a,b,c,d & e):

// State, with reasons, which loop structure you think would be most
// appropriate for solving each of the following problems.  Do NOT
// actually solve the problem in each part.

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

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

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

        // Question 4 (a):

        // Use a FOR loop that repeats 100 times, starting at 1 and
        // ending at 100, declare 'sum' as an int type, cube each index
        // value of the FOR loop and add it to the 'sum' --> use Math.pow(i,3)
        // with 'i' being the index.  Output the results ('sum') after the
        // FOR loop is done.

        // Question 4 (b):

        // Use a DO loop to first prompt the user for a user ID and password.
        // Compare the input password to a constant stored in the program.
        // If they match, exit the DO loop and tell the user he/she is now
        // logged in.  However, if they do NOT match, keep the user in the
        // DO loop until he/she enters a password that matches the one
        // stored in the program.

        // Question 4 (c):

        // Use a WHILE loop to keep entering only positive integers (> 0).
        // The user should first be prompted for a positive integer.  The
        // WHILE loop condition, now being true, allows entry into the loop.
        // As long as the WHILE loop condition is TRUE, keep entering positive
        // integers in the loop.  Only exit the WHILE loop when a sentinel value
        // (-1) is entered.

        // Question 4 (d):

        // Use a FOR loop to count the number of times a positive integer is
        // evenly divisible by 2 (using modulus), starting at 100. If the
        // division of the integer by 2 is even, there is no remainder, and
        // 1 should be added to a counter.  However, if the integer cannot be
        // evenly divided by 2, there will be a remainder, so the counter should
        // not be incremented by 1.  At the end of the repetition (to 400),
        // output the number of times a positive integer was evenly divisible
        // by 2.

        // Question 4 (e):

        // Use a FOR loop to accumulate the simple interest earned at 8%
        // on $1.00 for 10 years.  The FOR loop will repeat 10 times, once
        // for each year, and the interest for 1 year (1.00 * 0.08) will be
        // added to the total interest. After the FOR loop is done, output
        // what $1.00 is worth after 10 years at 8% interest per year.

    } // main method
} // Exercise45D_Chapter4 class

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

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

// Describe what the fragment does and re-write it using a DO-WHILE statement.

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

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

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

        // Question 3 (a):

        // 1) prompt the user for a positive integer (0 to stop).
        // 2) read in a positive integer ('value').
        // 3) assign 'value' to 'biggest'.
        // 4) in a WHILE loop, compare 'value' to 0 (value != 0).
        // 5) in an IF statement, if ('value' > 'biggest') is true,
        //    assign 'value' to 'biggest'.
        // 6) prompt the user for another positive integer (0 to stop).
        // 7) read in a positive integer ('value') (0 to stop).

        // Re-written as a DO-WHILE loop:

        int value, biggest = 0;
        do
        {
            c.println ("Enter any integer value - 0 to stop: ");
            c.println ("Calculate the positive value of any negative integer");
            c.println ("then, print out the biggest value you entered");
            c.println ();
            value = Math.abs (c.readInt ()); // makes the input positive
            if (value > biggest)
            {
                biggest = value;
            }
        }
        while (value != 0);
        c.println ("The biggest value you entered is: " + biggest);

        // Question 3 (b):

        // 1) in a FOR loop, must declare and initialize 'i' to 0.
        // 2) in a FOR loop, compare 'i' to 0 (i == 0).
        // 3) in a FOR loop, no incrementation / decrementation occurs.
        // 4) prompt the user as to whether they should continue (Y/N).
        // 5) read in the user's response as a character (Y/N).
        // 6) in an IF statement, if (response == 'Y' || response == 'y'),
        //    then assign 1 to 'i'.  DO loop ends only when the user
        //    reads in 'N' or 'n' to the user prompt to continue.

        // Re-written as a DO-WHILE loop:

        int i = 0;
        char response = 'y';
        do
        {
            if (response == 'N' || response == 'n')
            {
                i = 1;
            }
            c.println ("Continue? (Y/N)");
            response = c.readChar ();
        }
        while (i == 0);
        c.println ("i = " + i);
        c.println ("That's all folks!");

    } // main method
} // Exercise45C_Chapter4 class

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

// Exercise 4.5 - Question 2 (a & b):

// Describe what the fragment does and then re-write it using
// a WHILE statement.

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

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

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

        // Question 2 (a):

        // 1) in a FOR loop, 'i' must be declared and initialized to 0.
        // 2) in a FOR loop, 'i' is compared to 10 (i < 10).
        // 3) in a FOR loop, 'i' is incremented by 1.
        // 4) in the body of the FOR loop, x = 2 * i - 10 is calculated.
        // 5) in the body of the FOR loop, y = Math.abs (x / 5 - 2) is
        //    calculated.
        // 6) in the body of the FOR loop, both 'x' and 'y' are printed out.
        // NOTE:  'x' and 'y' should also be declared as type int, but are not.

        // Re-written as a WHILE loop:

        int i = 0, x, y;
        while (i < 10)
        {
            x = 2 * i - 10;
            y = Math.abs (x / 5 - 2);
            c.println (x + " " + y);
            i++;
        }

        // Question 2 (b):

        // 1) 'product' must be declared and initialized to 1.
        // 2) in a DO loop, there is a prompt to the user to enter
        //    the next value (an integer called 'next').
        // 3) 'next' is a value that is input by the user.
        // 4) in an IF statement, 'next' is compared to 'TERMINATOR'
        //    (next != TERMINATOR).
        // 5) in a calculation --> product *= next is performed.
        // 6) in the WHILE condition at the bottom of the DO loop,
        //    the condition (next != TERMINATOR) must be true to stay
        //    in the DO loop.
        // NOTE:  'product' should be displayed before the user is
        // prompted for another integer value.

        // Re-written as a WHILE loop:

        int product = 1, next;
        final int TERMINATOR = -1;
        c.println ("Enter the first integer (-1 to exit): ");
        next = c.readInt ();
        while (next != TERMINATOR)
        {
            product *= next;
            c.println ("product of 'i' is: " + product);
            c.println ("Next value please (-1 to exit): ");
            next = c.readInt ();
        }

    } // main method
} // Exercise45B_Chapter4 class

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

// Exercise 4.5 - Question 1 (a & b):

// Describe what the fragment does and then re-write it using a FOR
// statement.

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

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

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

        // Question 1 (a):

        // 1) declares 'count' and initializes it to 1.
        // 2) in a while loop, prints out 'count' and the square root
        // of 'count'.
        // 3) adds 1 to 'count' in the while loop.

        // Re-written as a FOR statement:
        for (int count = 1 ; count < 10 ; count++)
        {
            c.println (count + "\t" + Math.sqrt (count));
        }

        // Question 1 (b):

        // 1) declares and initializes 'i' to 5.
        // 2) in a do loop, decrements 'i' by 1.
        // 3) in a do loop, prints out 'i' to the power of 3.
        // 4) at the end of the do loop, the while condition must be
        //    true (i > 0) to stay in the do loop.

        // Re-written as a FOR statement:
        for (int i = 5 ; i > 0 ; i--)
        {
            c.println (Math.pow (i, 3));
        }

    } // main method
} // Exercise45_Chapter4 class

// 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

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

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

// Rewrite each fragment as a single FOR statement whose body
// consists of only an empty statement (as illustrated in Example 2
// in which only a semi-colon appears in the body of the FOR loop).

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

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

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

        // Question 2 (a):  (rewritten FOR statement)
        // will print the products of 'i':

        for (int product = 1, i = 10 ; i > 0 ; c.println (product),
                product *= i, i--)
            ;
        c.println ();

        // Question 2 (b):

        for (int i = 0, max = 0, j = 10 ; i < 10 || (i * j > max) ;
                max = i++ * j--,
                c.println (max))
                   ;

    } // main method
} // Exercise44B_Chapter4 class

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

// Exercise 4.4 - Question 1 (a,b & c):

// Using Variations on FOR loops.
// Assuming that all variables are of type int, determine the
// output of each fragment.

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

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

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

        // Question 1 (a):

        // uses 2 indices: 'i' and 'j', both of type int:
        for (int i = 1, j = 12 ; i < j ; i++, j -= 2)
        {
            c.println ("i = " + i + " j = " + j);
        }
        c.println ();

        // Question 1 (b):

        // uses 2 indices, 'i' and 'product', both of type int
        // and produces products of 'i'
        for (int i = 1, product = 1 ; i <= 5 ; product *= i, i += 2)
        {
            c.println ("product = " + product);
        }
        c.println ();

        // Question 1 (c):

        // uses 2 indices, 'n' and 'i', both of type int -->
        // but, will it produce anything?
        for (int n = 5, i = 1 ; n > 1 ; c.println (i), n--, i *= 2)
            ;

    } // main method
} // Exercise44_Chapter4 class

// 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

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

// Exercise 4.3 - Question 5:

// Using a FOR loop.
// Write a program that reads a positive integer 'n' and then
// prints an "n-times-table" containing values up to 'n' * 'n'.
// For example, if the program reads the value 5, it should print
// only the following:
// 5 * 1 = 5
// 5 * 2 = 10
// 5 * 3 = 15
// 5 * 4 = 20
// 5 * 5 = 25

// Include 3 sets of outputs from this program

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

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

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

        c.println ("Enter a positive integer (> 0)");
        int integer = c.readInt ();

        for (int n = 1 ; n <= integer ; n++)
        {
            c.println (integer + " * " + n + " = " + integer * n);
        }

    } // main method
} // Exercise43D_Chapter4 class

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

// Exercise 4.3 - Question 3 (a,b,c,d & e):

// Write a fragment that uses a FOR statement to perform the indicated
// action for each part.

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

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

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

        // Exercise # 3 (a):

        // double sum = 0;
        // for (int x = 1; x <= 1000; x++)
        // {
        //     sum += 1/x;
        //     c.println ("sum during FOR loop: " + sum);
        // }
        // c.println ("final sum: " + sum);
        // adds all the terms up to produce the final 'sum' value
        // after the FOR loop is finished

        // Exercise # 3 (b):

        // double sum2 = 0;
        // for (int i = 100; i <= 5000; i += 100)
        // {
        //     sum2 += Math.sqrt (i);
        //     c.println ("sum2 during FOR loop: " + sum2);
        // }
        // c.println ("final sum2: " + sum2);
        // // adds all the terms up to produce the final 'sum' value
        // // after the FOR loop is finished
        //
        // // Exercise # 3 (c):
        //
        // long product = 1;
        // for (int j = 1; j <= 20; j++)
        // {
        //     product *= j;
        //     c.println ("product during FOR loop: " + product);
        // }
        // c.println ("final product: " + product);
        // // multiplies all the terms to produce the final 'product' value
        // // after the FOR loop is finished
        //
        // // Exercise # 3 (d):
        //
        // int total = 0;
        // for (int m = -12; m <= 20; m++)
        // {
        //     total += (int)Math.pow(m,3);
        //     c.println ("total during FOR loop: " + total);
        // }
        // c.println ("final total: " + total);
        // // adds all the terms up to produce the final 'total' value
        // // after the FOR loop is finished
        //
        // // Exercise # 3 (e):
        //
        double sum3 = 1;
        for (double n = 2 ; n <= 25 ; n++)
        {
            sum3 += Math.pow (n, (1 / n));
            c.println ("sum3 during FOR loop: " + sum3);
        }
        c.println ("final sum3:\t" + sum3);

    } // main method
} // Exercise43C_Chapter4 class

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

// Exercise 4.3, Question 2 (a,b,c & d):

// Using a FOR loop.
// Write statements that will print a table of values
// for the function f(x) = 2x + 5 for the indicated
// values of 'x'.

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

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

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

        // Exercise # 2 (a):

        double fx = 0;
        for (int x = 6 ; x > 0 ; x--)
        {
            fx = 2 * x + 5;
            c.println (fx);
        }
        // produces the 'fx' values of: 17.0, 15.0, 13.0, 11.0, 9.0 and 7.0
        // for the indicated values of 'x'

        // Exercise # 2 (b):

        for (int x = 0 ; x <= 30 ; x += 3)
        {
            fx = 2 * x + 5;
            c.println (fx);
        }
        // produces the 'fx' values of: 5.0, 11.0, 17.0, 23.0, 29.0, 35.0, 41.0,
        // 47.0, 53.0, 59.0 and 65.0 for the indicated values of 'x'

        // Exercise # 2 (c)

        for (int x = -15 ; x <= 15 ; x += 5)
        {
            fx = 2 * x + 5;
            c.println (fx);
        }
        // produces the 'fx' values of: -25.0, -15.0, -5.0, 15.0, 25.0
        // and 35.0 for the indicated values of 'x'

        // Exercise # 2 (d)

        for (int x = 1 ; x < 1024 ; x *= 2)
        {
            fx = 2 * x + 5;
            c.println (fx);
        }
        // produces the 'fx' values of: 7.0, 9.0, 13.0, 21.0, 37.0, 69.0,
        // 133.0, 261.0, 517.0 and 1029.0 for the indicated values of 'x'

    } // main method
} // Exercise43B_Chapter4 class

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

// Exercise 4.3, Question 1 (a,b,c & d):

// Using a FOR loop in Java.
// Exercise 4.3, Question 1 --> a,b,c and d.
// What does each statement print?

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

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

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

        // Exercise # 1 (a):

        for (int i = -3 ; i <= 3 ; i++)
        {
            c.println ("*");
        }
        // produces 7 stars - one per line
        c.println ();

        // Exercise # 1 (b):

        for (int countDown = 5 ; countDown > 0 ; countDown--)
        {
            c.println (countDown + " seconds (till blast off)!");
        }
        // countDown starts at 5 and counts down to 1 (0 does not show)
        c.println ();

        // Exercise # 1 (c):

        for (char letter = 'P' ; letter <= 'S' ; letter++)
        {
            c.println ("Give me a " + letter);
        }
        // produces letters starting with 'P' and ending at 'S', inclusive
        c.println ();

        // Exercise # 1 (d):

        for (int i = 2 ; i < 100 ; i *= i)
        {
            c.println ("i = " + i);
        }
        // produces multiples of 'i' where 'i' starts at 2 and
        // ends at 100
        // ends at 'i' = 16 because the last multiplication
        // would result in 16 * 16 = 256
        c.println ();

    } // main method
} // Exercise43_Exercise1 class

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

// Exercise 5 of Chapter 4.1:

// Write a program that prompts the user for a sequence of integers,
// using 0 as a sentinel.  The program should count the number
// of times that consecutive values are equal.  For example, if the input
// is: 3  6  7  7  4  4  4  6  0, then the program should determine that
// there are 3 cases in which consecutive values are equal (using a
// nested WHILE loop).

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

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

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

        int number2 = 0;

        c.println ("Enter a series of integers, end with 0");
        int number = c.readInt ();

        int count = 0;

        // to continually input integers (use an outer while loop)
        // until the sentinel (0) is read
        while (number != 0)
        {
            c.println ("Insert next integer: ");
            number2 = c.readInt ();

            // to continually see if 2 consecutive input numbers match
            // (use an inner while loop)
            while (number == number2)
            {
                count++;
                number++;
            }
            number = number2;
        }

        c.println ("The number of cases of identical consecutive integers "
                + " is " + count + ".");

    } // main method
} // Exercise41C_Chapter4 class

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

// Question 4 of Exercise 4.1:

// Using a WHILE loop, determine which integer input value is less than
// or equal to 2 to the power of 'n'.  For example, if the input number
// is 25, then 32 = 2 to the power of 5, which is when the for loop stops.
// (NOTE: 'x' is the base and 'y' is the power in this exercise.)

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

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

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

        c.println ("Please enter a positive integer (>= 0)");
        int number = c.readInt ();

        int y = 0;            // this is the power variable (increases by 1)
        int x = (int) Math.pow (2, y); // exponents are always double values

        while (number > x)
        {
            y++;
            x = (int) Math.pow (2, y);
            c.println ("x: " + x);

        }
        c.print (x + " or " + "2 ^ " + y
                + " is greater than or equal to "
                + number + ".");


    } // main method
} // Exercise41B_Chapter4 class

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

// Questions 1, 2 and 3 of Exercise 4.1 (WHILE loops):

// Questions 1 and 2 can be answered in text here, but
// Question 3 consists of Java code which must be runnable
// in order to produce output.

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

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

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

        // Question 1:
        // What is the minimum number of times that the body of a while
        // statement can be executed?  0 times.

        // Question 2:
        // What is the maximum number of times that the body of while
        // statement can be executed?  No maximum.

        // Question 3:
        // What will be printed by this fragment?
        int m = 10;
        int n = 0;
        while (m > n)
        {
            c.println ("m = " + m + " n = " + n);
            m--;
            n += 2;
        }

    } // main method
} // Exercise41_Chapter4 class

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

// Example 1A shows how WHILE loops work in Java.
// This program is called "PrintSquares" and prints
// out the input values and their squares as long as
// the input values are not 0.

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

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

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

        c.println ("Give an integer, 0 to stop");
        int value = c.readInt ();

        while (value != 0)
        {
            c.println (value + " " + value * value);
            c.println ("Next integer, please (0 to stop)");
            value = c.readInt ();
        }

    } // main method
} // Example1A_Chapter4 class

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

// Example 1 shows how DO-WHILE statements work in Java.
// The user must enter a value from 1 to 10 to exit this loop.
// Any other value will keep them in the loop.

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

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

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

        int value;

        do
        {
            // use a DO-WHILE loop for validation of a value:
            c.println ("Give an integer (1-10)");
            c.println ("which will get you out of this DO-WHILE loop");
            value = c.readInt ();

        }
        while (value < 1 || value > 10);

    } // main method
} // Example1_Chapter4 class

// The "Calculate" class.
// Shows how to use variable and constant names to do calculations,
// in this case, the circumference and the area of a circle.

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

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

    public static void main (String[] args)
    {
        c = new Console ();
        // declare a constant for radius with value = 3
        final double radius = 3;
        // declare a constant for PI with value = 3.14159
        final double PI = 3.14159;
        // declare variables for circumference and area of a circle
        double circumf, area;
        // output the calculated values --> INCORRECT CALCULATION:
        // c.println ("circumference of a circle with diameter of 6 = "
        //            + PI / (radius*2));
        // CORRECT CALCULATION (for circumference):
        c.println ("circumference of a circle with diameter of "
                + (radius * 2) + " = " + 2 * PI * radius);
        // output the calculated values ---> INCORRECT CALCULATION:
        // c.println ("area of a circle with radius of 3 = "
        //            + PI * (radius * radius)
        // CORRECT CALCULATION (for area):
        c.println ("area of a circle with radius of " + radius + " = "
                + PI * (radius * radius));

    } // main method
} // Calculate class

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

// Finding the value of each trigonometric
// expression using Math.sin, Math.cos, Math.tan, Math,atan
// and Math.asin.

// Display the exact output of each of the following statements,
// with your answer rounded up to the nearest 2 decimal places.

public class MathMethodExercises2A
{
    public static void main (String[] args)
    {
        // Part (2a) -- Math.sin:
        System.out.println (Math.sin (Math.PI / 9));
        //_____________________________________
        // return type is float
        // Part (2b) -- Math.cos:
        System.out.println (Math.cos (Math.PI / 6));
        //_____________________________________
        // return type is float
        // Part (2c) -- Math.cos:
        System.out.println (Math.cos (1));
        //_____________________________________
        // return type is float
        // Part (2d) -- Math.atan:
        System.out.println (Math.tan (0));
        //_____________________________________
        // return type is float
        // Part (2e) -- Math.atan:
        System.out.println (Math.atan (Math.tan (0)));
        //__________________________________________
        // return type is float
        // Part (2f) -- Math.asin:
        System.out.println (Math.asin (Math.sin (Math.PI / 9)));
        //____________________________________________________
        // return type is float

    } // main method
} // MathMethodExercises2A class

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

// Using the methods: Math.round, Math.ceil
// and Math.floor. Display the exact output
// of the following statements, rounded up
// to the nearest 2 decimal places.

public class MathMethodExamples3A
{
    public static void main (String[] args)
    {
        // Part 3 (a, b & c) -- Math.round:
        System.out.println ("Math.round(7.2) = " + (Math.round (7.2)));
        //_______________________________________________
        System.out.println ("Math.round(5.4) = " + (Math.round (5.4)));
        //_______________________________________________
        System.out.println ("Math.round(-3.12) = " + (Math.round (-3.12)));
        //_______________________________________________
        // Part 3 (d and e) -- Math.floor:
        System.out.println ("Math.floor(94.21) = " + (Math.floor (94.21)));
        //_______________________________________________
        System.out.println ("Math.floor(9.9) + " + (Math.floor (9.9)));
        //_______________________________________________
        // Part 3 (parts f, g and h) -- Math.ceil:
        System.out.println ("Math.ceil(8.18) = " + (Math.ceil (8.18)));
        //_______________________________________________
        System.out.println ("Math.ceil(-5.47) = " + (Math.ceil (-5.47)));
        //_______________________________________________
        System.out.println ("Math.ceil(-8.5) = " + (Math.ceil (-5.8)));
        //_______________________________________________

    } // main method
} // MathMethodExamples3A class

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

// Example--Parts 1, 2 and 3:  Using Math.abs, Math.sqrt
// and Math.pow.

// Display the exact output of each of the following statements
// with your answer rounded up to the nearest 2 decimal places.
// Part 1: Math.abs returns any type except for boolean.
// Part 2: Math.sqrt returns the square root of the given positive value.
// Part 3: Math.pow returns the given positive value to its given power.

public class MathMethodExamples1A
{
    public static void main (String[] args)
    {
        // Part 1 (a, b, c & d) -- Math.abs:
        System.out.println ("Math.abs(-13) = " + (Math.abs (-13)));
        //_________________________________________
        System.out.println ("Math.abs(7.2) = " + (Math.abs (7.2)));
        //_________________________________________
        System.out.println ("Math.abs(-4.4e-3) = " + (Math.abs (-4.4e-3)));
        //_________________________________________
        System.out.println ("Math.abs(-645) = " + (Math.abs (-645)));
        //_________________________________________
        // Part 2 (a, b & c) -- Math.sqrt:
        System.out.println ("Math.sqrt(36) = " + (Math.sqrt (36)));
        //_________________________________________
        System.out.println ("Math.sqrt(7.0) = " + (Math.sqrt (7.0)));
        //_________________________________________
        System.out.println ("Math.sqrt(-7.0) = " + (Math.sqrt (-7.0)));
        //_________________________________________
        // Part 3 (a, b, c & d) -- Math.pow:
        System.out.println ("Math.pow(9, 1.0/3.0) = " + (Math.pow (9, 1.0 / 3.0)));
        //_________________________________________
        System.out.println ("Math.pow(3, 10) = " + (Math.pow (3, 10)));
        //_________________________________________
        System.out.println ("Math.pow(-32.0, 2) = " + Math.pow (-32.0, 2));
        //_________________________________________
        System.out.println ("(int)Math.pow(100, 0.25) = " + ((int) Math.pow (100, 0.25)));
        //_________________________________________

    } // main method
} // MathMethodsExamples1 class

Wednesday, 17 December 2014

// The "TablesAndArraysExample4B" class.  Page 311.
// (from the Carter book)

// Example 4 (B):

// Suppose that we wanted to store the sequence with terms, as follows:
//
//  t1 = 1/2, t2 = 1/4,....t5 = 1/32
//
// in an array of double values.  We could create and initialize such an
// array by writing the following:
//
public class TablesAndArraysExample4B
{
    public static void main (String[] args)
    {
        // declare and initialize the "terms" array as follows:

        double[] terms = {0.0, 0.5, 0.25, 0.125, 0.0625, 0.03125};

        // Note: the location at "ti" zero (i = 0) does not have be used.
        // Now, do the same thing, using the "terms2" array instead:

        double[] terms2 = { (double) 0.0, (double) 1 / 2, (double) 1 / 4,
            (double) 1 / 8, (double) 1 / 16, (double) 1 / 32};

        // This would store the value "t2i" at the location with index "i".
        // Again, the location at "t2i" zero (i=0) does not have to be used.
        //
        // now, view the contents of both of the arrays "terms" and "terms2":

        for (int m = 1 ; m < 6 ; m++)
        {
            System.out.print ((double) (terms [m]) + " ");
        } // end of for loop # 1

        System.out.println ();

        for (int n = 1 ; n < 6 ; n++)
        {
            System.out.print ((double) (terms2 [n]) + " ");
        } // end of for loop # 2

        System.out.println ();

    } // main method
} // TablesAndArraysExample4 class

// The "TablesAndArraysExample4" class.  Page 311.
// (from the Carter book)

// Example 4:

// Although Java's arrays are always indexed from zero,
// sometimes the values that we are dealing with are more
// naturally indexed from some other value(1).
//
// 1. Suppose, for example, that we wanted to store the
// values of a sequence called "terms" with elements: t1, t2,
// t3,...tn.  We could use an array of length 'n', but then
// t1 would be stored in the location with index 'i-1'.
// 2. A better alternative to doing the above, would be to
// declare the array to be of size 'n+1' and then store the
// element 't1' at location 'i' with the location at index
// zero being unused / ignored.  See the example code below.

public class TablesAndArraysExample4
{
    public static void main (String[] args)
    {
        // to store the values: t1=1/2, t2=1/4,...t5=1/32,
        // we need an array of type double to store these types
        // of values.  We could create and initialize such an
        // array by doing this:

        double[] terms = {0.0, 0.5, 0.25, 0.125, 0.0625, 0.03125};

        // This would store the element 't' at location 'i'.
        // The location with index zero (location 'i-1') would be unused
        // by inserting the value 0.0 in that location.
        // Now, do Exercises 8.1 # 1 - 5 in pages 312-313 for practice.

    } // main method
} // TablesAndArraysExample4 class

// The "TablesAndArraysExample3" class.  Page 311.
// (from the Carter book)

// Example 3:

// Java has an alternative form of array declaration
// that allows us to initialize an array with any values
// we like.  The statement below declares an int array
// called "primes", with enough space to hold only 10
// prime numbers and assigns prime number values.
//
// 1. Notice in this example the absence of the keyword 'new'
// and the use of brace brackets rather than square brackets
// on the right side of the assignment operator.
// 2. In addition, the size of the array is not stated explicitly;
// Java knows that the array is of length 10 because there are
// 10 values inside of the brace brackets.
// 3. The values inside of the brace brackets need not be constants;
// They can be expressions which will be evaluated at the time the
// program is executed.
// 4. The only restriction on these expressions is that they all be
// of the same type, since arrays are collections of values of the
// same type, in this case, int.

public class TablesAndArraysExample3
{
    public static void main (String[] args)
    {
        int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

    } // main method
} // TablesAndArraysExample3 class

// The "TablesAndArraysExample2" class.  Page 310.
// (from the Carter book)

// Example 2:

// The following fragment declares an int array
// called "list" of size 20.
//
// 1. Once an array has been declared, its size is fixed
// for the duration of its existence.
// 2. Every array object has a 'length' field whose value
// can be obtained by appending '.length' to the array's
// identifier --> <identifier>.length will tell you how
// long the array is.
// 3. Since arrays are always indexed from 0, the length
// of an array is one longer than the highest index
// in the array.

public class TablesAndArraysExample2
{
    public static void main (String[] args)
    {
        // int types include: byte, short, long, as well as int
        byte b = 10;
        // the array called "list" has 2 * 10 (or 20 elements)
        // since b == 10 and 2 * b = 20.
        int[] list = new int [2 * b];

    } // main method
} // TablesAndArraysExample2 class

// The "TablesAndArraysExample1" class.  Page 309.
// (from the Carter book)

// Example 1:

// The temperatures of a solution over a 6-minute interval
// are recorded in the following table:
// Time (min.)  0       1       2       3       4       5       6
// Temp.(deg.C) 32.0    27.2    24.4    22.7    21.6    21.0    20.6
//
// An array "temp" could be used to record the temperatures of a solution
// each minute, as follows:
// 1. The identifier of the array is "temp".
// 2. The identifiers of the elements are: temp[0], temp[1],...temp[6].
// 3. The values of the elements are 32.0, 27.4,....20.6.
// 4. The indices of the elements are 0, 1, 2,...6.

public class TablesAndArraysExample1
{
    public static void main (String[] args)
    {
        // to declare an array called "temp" of type double:
        double[] temp;
        // to create an array called "temp" with 6 elements:
        temp = new double [6];  // temp[0] does not have to be used
        // or, combine the declaration and creation of the "temp" array
        // of type double:
        double[] temp = new double [6];
        // the declaration and creation of the "temp" array makes
        // enough space in memory for 6 double numbers.

    } // main method
} // TablesAndArraysExample1 class

// The "UsingArraysExample3" class.  Page 315-316.
// (from the Carter book)

// Example 3:
//
// The method called "swap" shown below will switch the values
// of 2 elements in an array (called "list") of double values.

public class UsingArraysExample3
{
    // "swap" changes the values of list using i and j
    // to refer to the element numbers (and their values):
    public static void swap (double[] list, int i, int j)
    {
        double temp = list [i];
        list [i] = list [j];
        list [j] = temp;
    } // swap method


    // call the method "swap" from "main":
    public static void main (String[] args)
    {
        System.out.println ("Using Arrays - Example 3");
        System.out.println ();
        int i = 4, j = 4;
        double[] list = {7.3, 9.1, 3.3, 4.7, 6.0};
        // before "swap" was called:
        System.out.println ("Before:\n");
        for (int a = 0 ; a < list.length ; a++)
        {
            System.out.println (list [a]);
        } // end of for loop # 1

        swap (list, 1, 4);

        System.out.println ();
        System.out.println ("After:\n");
        // after "swap" was called:
        for (int a = 0 ; a < list.length ; a++)
        {
            System.out.println (list [a]);
        } // end of for loop # 2

    } // main method
} // UsingArraysExample3 class

// The "UsingArraysExample2A" class.  Page 315.
// (from the Carter book)

// Example 2:
//
// The method "join" creates a new array that contains the
// elements of each of the method's parameters and returns
// a reference to that array.
// Take a look at the code below, which illustrates this:

public class UsingArraysExample2A
{

    // this is the static method called "join" described above,
    // whioh will join double arrays "a" and "b" into another
    // double array "result":

    public static double[] join (double[] a, double[] b)
    {
        double[] result = new double [a.length + b.length];
        int i, j, k;

        // index through the "result" array and assign the values of
        // the array parameter called "a" to the elements of "result"
        // (the index is "i"):

        for (i = 0 ; i < a.length ; i++)
        {
            result [i] = a [i];
        } // end of for loop # 1

        // do the same thing using the "b" array parameter this time -->
        // (the index is "j" for the "b" array; include also another index "k"
        // which is also needed to access the element #'s 3-5 in "result"):
        for (j = 0, k = 3 ; j < b.length ; j++, k++)
        {
            result [k] = b [j];
        } // end of for loop # 2

        // output all elements of "result" (element #'s 0-5):

        System.out.println ("the 'result' array element #'s and values:");

        for (int n = 0 ; n < result.length ; n++)
        {
            System.out.println (n + "\t" + result [n]);
        } // end of for loop # 3


        // return the array 'result' to the "main" method:
        return result;
    } // join method


    // this is the "main" method, which calls the method
    // called "join"
    public static void main (String[] args)
    {
        System.out.println ("Using Arrays - Example 2");
        System.out.println ();
        // declare 2 arrays, "a" and "b", in the "main" method;
        // these 2 double arrays will then be passed as parameters to
        // the method "join":
        double[] a = {0.0, 0.1, 0.2};
        double[] b = {1.0, 1.5, 2.5};
        double[] result = new double [a.length + b.length];
        System.out.println ("Now, here is the new 'result' double array: ");
        System.out.println ();
        // call the method "join" and pass to it (by reference) the "a"
        // array and the "b" array as parameters to the "join" method:
        join (a, b);

    } // main method
} // UsingArraysExample2A class

// The "UsingArraysExample1B" class.  Page 314.
// (from the Carter book)

// Example 1B:  (continued from page 313):
//
// 6. Finally, notice the way we have written the condition
// that controls the for loop:
// as --> 'i < flags.length'.  The value of 'flags.length' is
// the size of the array, or, the number of elements in it.
// 7. As we have already noted, since an array is indexed
// from zero, the index of the last element is one less than
// the value of its length.
// 8. If we were to write the condition as --> 'i <= flags.length',
// we would be trying to access an element that is off the upper bound
// of the array.
// 9. But, if we attempt to use an index value that is out of the range
// of the array, Java 'throws an ArrayIndexOutOfBoundsException'
// (an error message) to let us know what we have done.
// 10. Because arrays, like other objects, are 'reference' types,
// they behave as other objects do when we try to manipulate them.
// 11. For example, suppose we make the declarations below:

public class UsingArraysExample1B
{
    public static void main (String[] args)
    {
        int[] p = {1, 3, 5, 7, 9};
        int[] q = {0, 2, 4, 6, 8};

        // 11 (con'd):
        // if we were now to write this assignment statement:

        p = q;

        // 11 (con'd):
        // this would copy the values from the array cells in q, to the
        // array cells in p.  The effect of this copying would be to have
        // p now refer to the same array values as q.  Since there is no longer
        // any reference to the array of odd numbers, these values are
        // no longer accessible to the program.

    } // main method
} // UsingArraysExample1B class
//
// Example 1B: (continued):
//
// 12. Comparison of arrays is like comparison of other objects in that,
// if p and q are array variables, the expression p == q will be true,
// if and only if, both p and q are referring to same array cells.
// It is NOT, however, a test of EQUALITY of the elements of 2 distinct
// arrays.  If we wanted to test for the equality of the contents of 2
// arrays, we should use a for loop that indexes through the 2 arrays,
// comparing corresponding array pairs for their contents.
// 13. Arrays, like all objects, can be parameters of methods (passed to
// methods as arguments) and returned from methods.

// The "UsingArraysExample1A" class.  Page 313.
// (from the Carter book)

// Example 1A:
//
// Having seen how to create arrays in Java, let us now
// examine some of the ways that we can operate on them
// and their elements.
//
// 1. The elements of an array can be treated like any other
// variable of that type.  We can assign values to them,
// print them, use them in expressions, and so on.
// 2. Often, we want to perform some operation on every
// element of an array.  We sometimes refer to this as
// 'indexing' through the array.
// 3. For example, if we wanted to create an array called
// "flags" containing 100 boolean values all set to true
// (rather than the standard initialization to false), we
// could use the code below:

public class UsingArraysExample1A
{
    public static void main (String[] args)
    {
        System.out.println ("Using Arrays - Example 1A");
        System.out.println ();
        boolean[] flags = new boolean [100];
        System.out.println ("boolean [] flags = new boolean [100];");
        // to cycle through (index through)
        // all of the array's elements, we do this:

        for (int i = 0 ; i < flags.length ; i++)
        {
            flags [i] = true;
        } // end of for loop # 1

        // now, if you want to see the values that the array
        // flags now holds, do this:
        for (int i = 0 ; i < flags.length ; i++)
        {
            System.out.println (i + "\t" + flags [i]);
        } // end of fro loop # 2

    } // main method
} // UsingArraysExample1A class
//
// Example 1A (continued):
//
// 4. In this example, we used a 'for' loop to index through
// the array. We also could have used a 'while' or 'dowhile'
//(a.k.a. 'do') loop to do the same thing, but using a 'for'
// loop is simplest.  It is almost always the case that a 'for'
// loop is the best way to index through an array.
// 5. Notice also the use of 'flags.length' to determine the
// upper bound of the array.  This is more reliable and probably
// clearer to a reader than using the value 100 instead.

// The "MultiDimensionalArraysExample8" class.  Page 324.
// (from the Carter book)

// Example 8:

public class MultiDimensionalArraysExample8
{
    public static void main (String[] args)
    {
        // Suppose that we were to declare a 2-dimensional array of type
        // double called "table" (with 40 rows and 60 columns maximum):

        double[] [] table = new double [40] [60];

        // We could then call the "process" method from "main" by writing
        // the following line and passing "table[20]" to the "process" method:

        process (table [20]);  // this argument passes 20 rows of "table"
        // to the "process" method (see below).

    } // main method


    // Suppose that a program had a method with the following header
    // defined:
    public static void process (double[] row)
    {
        // insert your method code here.
        // This works because "table [20]" is really a reference to a one-dimensional
        // array of double values, and that is an exact match to the type double
        // one-dimensional array parameter called "row".

    } // process method

} // MultiDimensionalArraysExample8 class

// The "MultiDimensionalArraysExample7" class.  Pages 323-324.
// (from the Carter book)

// Example 7:

// The following declarations are NOT legal.  See the notes
// below the declarations for clarification:

public class MultiDimensionalArraysExample7
{
    public static void main (String[] args)
    {
        // 7(a):  a 2-dimensional array of x * 50 float numbers.
        //        (the first dimension is unspecified, but is needed.
        float[] [] badOne = new float[] [50];
        //
        // 7(b):  a 3-dimensional array of 10 * x * 25 boolean values.
        //        (the second dimension is unspecified, but is also required
        //         when the first dimension is specified; the third dimension
        //         does not have to be specified, however, in a 3-D array).
        boolean[] [] [] badTwo = new boolean [10] [] [25];
        //
        // 7(a):  Note:  This attempt to create an unspecified number of arrays
        //               that are each of type float[50] will fail.  The first
        //               dimension must always be specified.
        //
        // 7(b):  Note2: Although the first dimension has been specified here,
        //               the second and third dimension show the same pattern
        //               that was exhibited in the "badOne" array declaration
        //               (see 7(a) above).
        //
        // Finally, we note that, just as one-dimensional array references can
        // be used as parameters (passed to methods) and return values from methods,
        // so too can multi-dimensional array references.  Of course, the dimensions
        // of arguments must match the parameters they are being passed to, and their
        // types must also be appropriate.  It is also possible to pass sub-arrays
        // (partially-filled arrays) to methods, as Example 8 will show.

    } // main method
} // MultiDimensionalArraysExample7 class

// The "MultiDimensionalArraysExample6" class.  Page 323.
// (from the Carter book)

// Example 6:

// 1. The following declarations are ALL VALID (see below):

public class MultiDimensionalArraysExample6
{
    public static void main (String[] args)
    {
        // (6a):  (all dimensions' sizes are specified):
        char[] [] [] goodOne = new char [5] [6] [3];
        // (6b):  (the last 2 dimensions' sizes are not specified):
        byte[] [] [] goodTwo = new byte [20] [] [];
        // (6c):  (the last dimension's size is not specified):
        double[] [] [] goodThree = new double [50] [100] [];
        // (see below program for NOTES)

    } // main method
} // MultiDimensionalArraysExample6 class
//
// Example 6: (continued) --> NOTES:
//
// (6a):  This  first declaration creates an array of 5 * 6 * 3 = 90 char
// elements or, more accurately, five sets of six sets of 3-element
// char arrays.
// (6b):  This second declaration creates 20 arrays of type byte [][].  Each
// of these 20 arrays (called "goodTwo[0], goodTwo[1], and so on) will all
// be initialized to null (because no size is specified for the other 2
// dimensions).
// (6c):  This third declaration creates an array of 50 references to arrays of
// 100 references to arrays with elements of type double.  These 5,000
// array references will all be set to null (because no size is specified for
// the last dimension).

// The "MultiDimensionalArraysExample5" class.  Page 322-323.
//  (from the Carter book)
//
// Example 5: 

// 1. The following fragment could be used to find the
// sum of the elements of a ragged 2-dimensional array,
// like the one shown in Example 4.  Notice that the upper
// bound of the inner for loop now depends on the length
// of each row of the array, as they each differ in length
// First, re-declare the "ragged" array here for this
// example.

public class MultiDimensionalArraysExample5
{
    public static void main (String[] args)
    {
        int[] [] ragged = {{4, 3, 7},
                {5, 2},
                {7, 8, 1, 4}};

        int sum = 0;

        for (int row = 0 ; row < ragged.length ; row++)
        {
            for (int col = 0 ; col < ragged [row].length ; col++)
            {
                // sum up the elements in each row of the
                // "ragged" array --> the "col" value (length)
                // is different for each row
                sum += ragged [row] [col];
                System.out.print (ragged [row] [col] + " ");
                System.out.print (" += ");
                System.out.println (sum);
            } // end of inner for loop
        } // end of outer for loop

    } // main method
} // MultiDimensionalArraysExample5 class
//
// Example 5: (continued):
//
// 2. Multi-dimensional arrays are NOT limited to only 2 dimensions.
// We can create 3-dimensional arrays, 4-dimensional arrays, or arrays of
// even higher dimensions.  These higher-dimensional arrays are usually
// rectangular, but they need not be.
// 3. We suggested that a 2-dimensional rectangular array could be visualized
// as a table with rows and columns.  Similarly, a rectangular 3-dimensional
// array could be visualized as a set of tables, perhaps a book containing
// a number of tables, one per page.  The indices could be thought of as
// representing the pages, rows and columns (in that order).
// 4. A 4-dimensional array could then be thought of as a number of volumes
// of books, all of the same size, with an index specifying a volume, page,
// row and column.  As with 2-dimensional arrays, we need not specify all of
// the dimensions in a declaration of a higher-dimensional array.

// The "MultiDimensionalArraysExample4" class.  Page 321-322.
// Example 4.  (from the Carter book)

// Array declarations, like the one in Example 3 ("triTable"),
// in which the second (column) dimension's size is unspecified,
// are legal.  However, it is not legal to have the first (row)
// dimension's size unspecified.  For example, look at this
// illegal declaration, as follows:

public class MultiDimensionalArraysExample4
{
    public static void main (String[] args)
    {
        //int [] [] badArray = new int [] [20];
        //
        // this declaration is not permitted. During compilation, the error
        // message will read: "Expression expected after this token"
        // --> meaning that the first (row) dimension must have a size
        // specified inside the first [].
        //
        // Non-rectangular 2-dimensional arrays are sometimes
        // called "ragged arrays".  We can initialize ragged
        // arrays in their declarations, just as we did for
        // rectangular arrays, as follows:

        int[] [] ragged = {{4, 3, 7},
                {5, 2},
                {7, 8, 1, 4}};

        // this declaration creates the array called "ragged" whose
        // length of each row may be different, which we can see, as follows:

        for (int row = 0 ; row < ragged.length ; row++)
        {
            System.out.println ();
            // "col" may not vary at the same rate as "row" -->
            // (there could be more, less, or the same col length
            //  compared to row length)
            for (int col = 0 ; col < ragged [row].length ; col++)
            {
                System.out.print (ragged [row] [col] + " ");
            } // end of inner for loop
        } // end of outer for loop

        System.out.println ();

    } // main method
} // MultiDimensionalArraysExample4 class

// The "MultiDimensionalArraysExample3" class.  Page 321.
// Example 3.  (from the Carter book)

// The following program fragment creates a triangular
// array of double values (0.0) with one element in the first
// row, two elements in the second row, and so on, for
// a total of five rows:

public class MultiDimensionalArraysExample3
{
    public static void main (String[] args)
    {
        // note the absence of a column dimension in this
        // declaration but, the row dimension is legally required
        double[] [] triTable = new double [5] [];
        // configure this triangular array with the following code:

        for (int row = 0 ; row < triTable.length ; row++)
        {
            // you only need to refer to the row dimension here,
            // since there is no column dimension specified -->
            // (add one to each row of this array):

            triTable [row] = new double [row + 1];
        } // end of for loop

        // we can picture the resulting triangular shape of
        // the "triTable" array, as follows:

        for (int row = 0 ; row < triTable.length ; row++)
        {
            System.out.println (); // force a return at the end of each row
            // a virtual "col" may usually vary at the same rate as "row"
            for (int col = 0 ; col <= row ; col++)
            {
                System.out.print (triTable [row] [col] + " ");
            } // end of inner for loop
        } // end of outer for loop

        System.out.println ();

    } // main method
} // MultiDimensionalArraysExample3 class

// The "MultiDimensionalArraysExample2" class.  Page 320 (bottom).
// Example 2.  (from the Carter book)

// Suppose we want to create a table with 3 rows and 4 columns, initialized
// as shown at the bottom of page 320.
// We can do this by declaring and intializing the "scores" array, as follows:

public class MultiDimensionalArraysExample2
{
    public static void main (String[] args)
    {
        int[] [] scores = {{5, 2, 7, 3},
                {6, 8, 7, 9},
                {4, 5, 2, 3}};

        // On the right side of the assignment statement, the elements of each row
        // of the array are enclosed by brace brackets and separated by commas.
        // Similarly, the sets of values for each row are themselves enclosed by
        // brace brackets and separated by commas.  The statement could have been
        // written all on one line, but we wrote it so that to make the structure of
        // the array called "scores" clearer to a human reader.
        // to view the element values of the "scores" array the way they appear
        // above, we should do this:

        for (int i = 0 ; i < scores.length ; i++)
        {
            System.out.println (); // a return makes one line of values per row
            for (int j = 0 ; j < scores [0].length ; j++)
            {
                System.out.print (scores [i] [j] + " ");
            } // end of inner for loop
        } // end of outer for loop

        // The 1-dimensional arrays that compose a 2-dimensional array need not all
        // be of the same length, as the next example (3) illustrates.

    } // main method
} // MultiDimensionalArraysExample2 class