// (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
No comments:
Post a Comment