Transcript Math 107

Introduction To
Scientific Programming
Chapter 6 – Arrays
Lecture Overview on
Arrays
I. Array Basics
II. Arrays in Classes and Methods
III. Sorting & Searching Arrays
IV. Multidimensional Arrays
S.Horton/107/Ch. 6
Slide 2
I. Array Basics

An array is a single name for a collection of data values (all
of the same data type)

A special subscript notation identifies precisely one of the
values of the collection

Arrays work like objects:


They are initialized like objects
There can be multiple arrays of the same type

Arrays are a natural fit for loops, especially for loops

However, they are not “full” objects

No real methods, constructors, or “inheritance”
S.Horton/107/Ch. 6
Slide 3
Creating Arrays

General syntax for declaring an array:
Base_Type[] Array_Name = new Base_Type[Length];

Examples:
80-element array with base type char:
char[] symbol = new char[80];
100-element array with base type double:
double[] reading = new double[100];
100-element array with base type AddressBook:
AddressBook[] homebook = new AddressBook[100];
S.Horton/107/Ch. 6
Slide 4
Three Uses of [ ] (Brackets)
with an Array Name
1. To
create an array type name, e.g. int[]
creates a name with the type "int array"

2. To
pressure;
The types int and “int array” are different
create a new array, e.g.
pressure = new int[100];
3. To
name a specific element in the array (also
called an indexed variable), e.g.
pressure[3] = SavitchIn.readLineInt();
System.out.println("You entered" + pressure[3]);
S.Horton/107/Ch. 6
Slide 5
An Array Declaration Can
Be “Broken-Up”
•
Last slide syntax was correct! Why? Because
you can break up declaration like any object
•
For example, the complete declaration:
int[] pressure = new int[100];
can be broken up into:
int[] pressure;
//first
part declaration
…
pressure = new int[100]; //second
part assignment
…
•
This can be handy for re-declaration (more on
this soon).
S.Horton/107/Ch. 6
Slide 6
Array Terminology
Array name
temperature[n + 2]
temperature[n + 2]
temperature[n + 2]
Index (also called a subscript)
- Must be an int, or an expression that
evaluates to an int
Indexed element/variable (also called a
subscripted variable)
temperature[n + 2] = 32;
Value of the indexed variable
(also called an element of
the array)
Note: an "element" may refer to either a single indexed variable
in the array or the value of a single indexed variable.
S.Horton/107/Ch. 6
Slide 7
Array Length

The length of an array is specified by the number given in the
brackets when it is created with new


This determines the maximum number of elements the array can
hold and the amount of memory allocated for the elements
The array length can always be read with the instance
variable length.

E.g. the following code displays the number 20 (this is the size, or
length of the double array, entry):
double[] entry = new double[20]; //20*8 bytes allocated
System.out.println(entry.length);

The length attribute is established in the declaration and cannot
be changed by the programmer unless the array is re-declared.
S.Horton/107/Ch. 6
Slide 8
Subscript Range

Any array subscript uses “zero-numbering”





The first element has subscript 0
The second element has subscript 1
The nth element has subscript n-1
The last element has subscript length-1
For example:
int[] score = new int[4];
…
(Score is assigned values 97, 86, 92, and 71)
…
Configuration:
S.Horton/107/Ch. 6
Subscript: 0
Value: 97
1
86
2
92
3
71
Slide 9
Subscript Issues & The
“Out of Bounds” Error

Using a subscript larger than length-1 causes a
run-time (not a compiler) error



An ArrayOutOfBoundsException is thrown
You need to fix the problem and recompile
Some other programming languages (most
noticeably C and C++) do not even cause a run
time error!



It is a dangerous characteristic (of any language) to allow out of
bounds array indexing.
Why? Because bounds checking requires extra overhead.
The most sophisticated compliers have the option to turn bounds
checking on and off.
S.Horton/107/Ch. 6
Slide 10
Initializing an Array's Values
in Its Declaration

Array declaration syntax allows element initialization by
using a comma-delimited list in curly braces.

To initialize an array, drop everything right of the equal
sign and add the value list.

For example:
int[] score = {97, 86, 92, 71};

The length of an array is automatically determined when
the values are explicitly initialized in the declaration.

If an array is un-initialized, all elements will be assigned
some default value, e.g. 0 for int arrays.
S.Horton/107/Ch. 6
Slide 11
Initializing Array Elements
in a Loop

Array processing is most commonly done in a loop.

A for loop is commonly used to initialize/work with arrays
and array elements.

Example:
int i;
//loop counter & array index
int[] a = new int[10];
…
For (i = 0; i < a.length; i++)
a[i] = 0;

The loop counter/array index goes from 0 to length – 1

Loop counts through 10 iterations using the zeronumbering of the array index (0-9).
S.Horton/107/Ch. 6
Slide 12
Array Programming Tips

Use singular rather than plural names for arrays unless
the data itself is plural. This improves readability.

For example:
System.out.println(“The top score=” + score[index]);


This is because, although the array contains many elements,
an array used with a subscript references a single value.
Do not count on default initial values for array elements

You should explicitly initialize elements in the declaration or
most commonly in a loop at the beginning of a method.
S.Horton/107/Ch. 6
Slide 13
II. Arrays in Classes and
Methods
• Arrays and array elements can be used with
classes and methods just like other objects.

Both an indexed array element and an array
name can be an argument in a method.

Both an indexed array element and an array
name can be returned by a method.
S.Horton/107/Ch. 6
Slide 14
An Indexed Array Element
As A Method Argument
nextScore is
an array of int
public static void main(String arg[])
{
int i, firstScore;
int[] nextScore = new int[3];
double possibleAverage;
System.out.println("Enter your score on exam 1:");
firstScore = SavitchIn.readLineInt();
for (i = 0; i < nextScore.length; i++)
nextScore[i] = 80 + 10*i;
for (i = 0; i < nextScore.length; i++)
{
possibleAverage = ave(firstScore,nextScore[i]);
System.out.println("If your score on exam 2 is "
+ nextScore[i]);
System.out.println(" your average will be "
+ possibleAverage);
}
an element of
nextScore is an
argument of
method average
}
average
method definition
S.Horton/107/Ch. 6
public static double ave(int n1, int n2)
{
return (n1 + n2)/2.0;
}
Slide 15
When Can a Method Change an
Indexed Array Element Argument?

When an array element is a primitive type:




A copy of the value is passed as an argument in method call
So, the method cannot change the value of the indexed array
element
This follows the “call-by-value” convention
When an array element is a class type:




The address of the object is passed as an argument in method call
So, the method can change the value of the indexed array element
This follows the “call-by-reference” convention
Note: the corresponding argument in the method definition becomes just
another name for the object
S.Horton/107/Ch. 6
Slide 16
Array Names as Method
Arguments

When you want to pass an entire array as an
argument to a method, just use the array name and
no brackets.

As previously described, any method that gets a nonprimitive type (the entire array, in this case) has
access to the original array and can change the value
of its’ elements.

Using the length attribute inside the method will
handle needing to know the size of the array and
avoid ArrayIndexOutOfBoundsException
S.Horton/107/Ch. 6
Slide 17
Example: An Array as an
Argument in a Method Call
public static void showArray(char[] a)
{
int i;
for(i = 0; i < a.length; i++)
System.out.println(a[i]);
}
S.Horton/107/Ch. 6
the method's argument
is the name of an array
of characters
uses the length
attribute
to control the loop
allows different size
arrays
and avoids index-out-ofbounds exceptions
Slide 18
Solving Another Mystery Arguments for the main Method

The declaration of a program’s main method defines a
parameter that is an array of type String:
public static void main(String[] args)

When you execute a program from the command line, all
words after the class name will be passed to the main
method in the args array.

The following main method in the class TestProgram
will print out the first two arguments it receives:
public static void main(String[] args)
{
System.out.println(“Options:“ + args[0] + “ “ + args[1]);
}
S.Horton/107/Ch. 6
Slide 19
Issues With Reference
Types

Consider the following:
int[] a = new int[3];
int[] b = new int[3];

With the code statement b = a; what do you get?



Since a and b are reference types, you get the address of a
assigned to the address of b (you basically give a the name b).
If you want to copy a to b, you need to use/write a clone method
With the code if (b == a) … what do you compare?

Since a and b are reference types, you check if the address of a
and the address of b are the same (i.e. are they exact same object).

If you want to check if the arrays are equal, you need to use/write
an equals method.
S.Horton/107/Ch. 6
Slide 20
Example: Using = With
Array Names
int[] a = new int[3];
int[] b = new int[3];
for(int i; i < a.length; i++)
a[i] = i;
b = a;
System.out.println(a[2] + " " + b[2]);
a[2] = 10;
System.out.println(a[2] + " " + b[2]);
This does not create a
copy of array a;
it makes b another
name for array a.
The output for this code will be:
2 2
10 10
S.Horton/107/Ch. 6
Slide 21
Example: Using == With
Array Names
int i;
int[] a = new int[3];
int[] b = new int[3];
for(i; i < a.length; i++)
a[i] = i;
for(i; i < b.length; i++)
b[i] = i;
a and b are both
3-element arrays of int
all elements of a and b are
assigned the value 0
if(b == a)
System.out.println("a equals b");
else
System.out.println("a does not equal b");
tests if the addresses
of a and b are equal,
not if the array values
are equal
The output for this code will be " a does not equal b"
because the addresses of the arrays are not equal.
S.Horton/107/Ch. 6
Slide 22
Testing Two Arrays for
Equality

To test two arrays
for equality you
need to define an
equals method

Return true if and
only the arrays
have the same
length and all
corresponding
values are equal

Can you write a
clone method now?
S.Horton/107/Ch. 6
public static boolean equals(int[] a, int[] b)
{
boolean match;
if (a.length != b.length)
match = false;
else
{
match = true; //tentatively
int i = 0;
while (match && (i < a.length))
{
if (a[i] != b[i])
match = false;
i++;
}
}
return match;
}
Slide 23
Methods That Return an
Array

Method vowels
returns an array of
type char[]

The array
newArray is not
passed back, the
address is passed
back.

Notice that the array
name within the
method is just
another name for
the original array c.
S.Horton/107/Ch. 6
public class returnArrayDemo
{
public static void main(String arg[])
{
char[] c;
//typed but not allocated
c = vowels();
for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
public static char[] vowels()
{
char[] newArray = new char[5];
}
}
newArray[0] = 'a';
newArray[1] = 'e';
newArray[2] = 'i';
newArray[3] = 'o';
newArray[4] = 'u';
return newArray;
c, newArray, and
the return type of
vowels are
all the same type:
char []
Slide 24
Wrapper Classes For
Arrays

Arrays can be made into objects by defining them in a class



In a well-defined array wrapper class, one can:





No special syntax, just define array in a class and add the
appropriate structure
Derives name from and similar in structure to wrapper classes for
primitive types
Make an array an instance variable
Define accessor/mutator methods to read and write element values
and parameters
Define constructors
Define .equals, .clone, .toString, .sort, …
This strategy leads to a number of very important data structures
that are discussed in Math 108 – linked lists, queues, stacks,
hash tables, etc…
S.Horton/107/Ch. 6
Slide 25
Watch For Partially Filled
Arrays

Sometimes only part of an array has been filled
with valid data

Array elements always contain something,
whether you have written to them or not


Elements which have not been written to contain
unknown (or garbage) data so you should avoid
reading them
There is no automatic mechanism to detect how
many elements have been filled – you need to
keep track!
S.Horton/107/Ch. 6
Slide 26
Example: Partially Filled
Array


entry is an array of type String.
countOfEntries is current size (pointer).
entry[0]
Buy milk.
entry[1]
Call home.
entry[2]
Go to beach.
entry[3]
""
entry[4]
""
countOfEntries - 1
garbage values
countOfEntries has a value of 3.
entry.length has a value of 5.
S.Horton/107/Ch. 6
Slide 27
III. Sorting an Array

One of the most common issues facing programmers is
to sort one or more arrays

You may need to:



Sort numbers in ascending or descending order
Sort characters or strings in alphabetic order
Sort one array and rearrange another based on first sort

There are many algorithms (or methods) to sort an
array. Some of the most common are Selection sort,
Quicksort, and Heapsort

Sorting algorithms have a number of attributes

Speed/Efficiency, Direction, Order Preservation, In-Place, etc..
S.Horton/107/Ch. 6
Slide 28
Selection Sort

Selection sort is one of the easiest to
understand and program

Also, one of the slowest – called O(n2)!

Great for rearranging multiple arrays based on
sorting one of them (think email)

Pseudocode for Selection sort:

For each index in the array


S.Horton/107/Ch. 6
Find the smallest value from the current index
Swap current index value with smallest value
Slide 29
Selection Sort:
Diagram of an Example
Problem: sort this 10-element array of integers in ascending order:
a[0]
7
a[1]
6
a[2]
11
a[3]
17
a[4]
3
a[5]
15
a[6]
5
a[7]
19
a[8]
30
a[9]
14
1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4]
before:
7
6
11
17
3
15
5
19
30
14
after:
3
6
11
17
7
15
5
19
30
14
2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6]
3
6
11
17
7
15
5
19
30
14
3
5
11
17
7
15
6
19
30
14
Etc. - only nine iterations are required since the last one will put
the last two entries in place by swapping them if necessary.
S.Horton/107/Ch. 6
Slide 30
Attributes Of Selection Sort

The SelectionSort program in your book shows a
class for sorting an array of int in ascending order.

Algorithm attributes:



Every indexed variable must has a value
If the array has duplicate values, they are put in
sequential positions (order preserving)
Note: sorting was defined in terms of smaller tasks, such
as "find the index of the smallest value" and “swap two
elements”

S.Horton/107/Ch. 6
These “subtasks” are written as separate methods and are
private because they are helper methods (external users
are not expected to call them directly)
Slide 31
Selection Sort Code
/**************************************************
* Sorts an array of integers. Every indexed
* variable of array a has a value. Requires helper
* routines indexOfSmallest & swap.
*
* Output: a[0] <= a[1] <= ... <= a[a.length - 1].
*
**************************************************/
public static void sort(int[] a)
{
int index, indexOfNextSmallest;
for (index = 0; index < a.length - 1; index++)
{
//Find the next smallest value from current position
indexOfNextSmallest = indexOfSmallest(index, a);
//Place the correct value in a[index]
swap(index,indexOfNextSmallest, a);
}
}
S.Horton/107/Ch. 6
Slide 32
Selection Sort Code - II
/**************************************************
* Returns an index in array a of the minimum value
* from a[startIndex] through a[a.length-1]
*
**************************************************/
private static int indexOfSmallest(int startIndex, int[] a)
{
int min = a[startIndex];
//Beginning min value
int indexOfMin = startIndex; //Index of beginning min value
int index;
for (index = startIndex+1; index < a.length; index++)
{
//Find min from a[startIndex] through a[index]
if (a[index] < min)
{
min = a[index];
indexOfMin = index;
}
return indexOfMin;
}
S.Horton/107/Ch. 6
Slide 33
Selection Sort Code - III
/**************************************************
* Swaps two elements in array a.
*
**************************************************/
private static void swap(int i, int j, int[] a)
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
//original value in a[i]
}
S.Horton/107/Ch. 6
Slide 34
Sorting Algorithm
Tradeoffs

There is always a tradeoff in
sorting algorithms between
efficiency and simplicity.
Comparison of Sort Efficieny



n^2 vs. nlog(n)
Selection Sort is:
Quicksort & Heapsort are:


1000000
Not very efficient: O(n2)
But, easy to code and make
modifications
n^2

Very efficient: O(nlog(n))
But, more complicated and
harder to modify
500000
0
0

Rule of thumb: If you have
more than 100 elements,
you should always use an
efficient sorting algorithm.
S.Horton/107/Ch. 6
500
1000
elements
Slide 35
Sorting in Java

Sorting is so common that Java provides a library of
routines to perform optimized O(nlog(n)) sorting and
searching

Import the package java.util.Arrays;

There are a number of static methods to perform inplace sorting and searching, e.g.
int[] ivalue = new int[1000];
…
Arrays.sort(ivalue);
S.Horton/107/Ch. 6
Slide 36
Bonus II - Selection Sort
Code For Multiple Arrays
/**************************************************
* Sorts two arrays of integers based on sorting a.
* Every indexed variable of array a has a value.
* Requires helper routines indexOfSmallest & swap.
*
* Output: a[0] <= a[1] <= ... <= a[a.length - 1].
*
Array b is sorted based on a
**************************************************/
public static void sort(int[] a, int[] b)
{
int index, indexOfNextSmallest;
for (index = 0; index < a.length - 1; index++)
{
//Find the next smallest value from current position
indexOfNextSmallest = indexOfSmallest(index, a);
//Place the correct value in a[index]
swap(index,indexOfNextSmallest, a);
swap(index,indexOfNextSmallest,b);
}
}
S.Horton/107/Ch. 6
Slide 37
Searching an Array

An equally common task to sorting an array is to
find a particular value in an array.

There are two basic approaches to searching an
array for a particular value – sequential search or
binary search.

The two main issues with searching:



How many times do you need to search?
What do you do if the value is not found?
An important extension to searching in an array is
searching in two-dimensional arrays or tables.
S.Horton/107/Ch. 6
Slide 38
Sequential Search

A sequential search is the easiest to understand
and program.

If you are only going to do it once, it is also the
fastest!

Sequential search pseudocode:

For each element in the array from the start



If value is equal to current index element, return index
If end of array is reached with no match, return 0
A sequential search of an array is an O(n) process.
S.Horton/107/Ch. 6
Slide 39
Sequential Search Code
/*********************************************
* This routine performs a sequential search of
* an array of integers. If ivalue is found,
* The index is returned. If no match is found,
* zero is returned.
*
* *********************************************/
public int ssearch(int[] a, int ivalue)
{
int i = 0;
for (;i < a.length; i++)
{
if (a[i] = ivalue) return i;
}
return 0;
}
S.Horton/107/Ch. 6
Slide 40
Sequential Search Code
/*********************************************
public static void showTable(int[][] displayArray)
{
int row, column;
for (row = 0; row < displayArray.length; row++)
{
System.out.print((row + 1) + "
");
for (column = 0; column < displayArray[row].length;
column++)
System.out.print("$" + displayArray[row][column] +
" ");
System.out.println();
}
}
S.Horton/107/Ch. 6
Slide 41
Searching An Array
Multiple Times

If you need to frequently search for items in an array,
sequential searching is inefficient.

A much quicker way is to use binary search.

Binary searching uses a divide and conquer algorithm
to quickly locate the value in roughly half the time of a
sequential search. This type of searching is an O(n/2)
process.

The issue is that a binary search only works on sorted
data. So, you must incur the extra overhead of sorting
the data first before performing binary searches.
S.Horton/107/Ch. 6
Slide 42
Searching in Java

Java provides a library of routines to perform
optimized searching.

Import the same package as before:
java.util.Arrays;

To perform multiple, efficient searches:
int[] ivalue = new int[1000];
int index1,index2,item1,item2,… ;
…
Arrays.sort(ivalue);
…
index1 = Arrays.binarySearch(ivalue,item1);
index2 = Arrays.binarySearch(ivalue,item2);
S.Horton/107/Ch. 6
Slide 43
IV. Multi-Dimensional
Arrays

The next logical extension to a one-dimensional array is
a two-dimensional array and so on…

Java handles multi-dimensional arrays by just adding an
index for each dimension (an array’s rank is how many
dimensions it has).

A two-dimensional (2-D) array can be thought of as a
table, grid, or matrix




The first dimension can be thought of as a row
The second dimension can be thought of as a column
A cell or value is the intersection of a row and a column
An array element corresponds to a cell in the table
S.Horton/107/Ch. 6
Slide 44
Representing A Table As A
2-Dimensional Array

The first dimension or row identifier is Year

The second dimension or column identifier is Percentage

Any cell contains a balance for a year and a percentage rate

Example: the balance for year 4 and rate of 7.00% = $1311
Year
1
2
3
4
5
…
S.Horton/107/Ch. 6
Balances for Various Interest Rates
Compounded Annually
(Rounded to Whole Dollar Amounts)
5.00% 5.50% 6.00% 6.50% 7.00%
$1050 $1055 $1060 $1065 $1070
$1103 $1113 $1124 $1134 $1145
$1158 $1174 $1191 $1208 $1225
$1216 $1239 $1262 $1286 $1311
$1276 $1307 $1338 $1370 $1403
…
…
…
…
…
Note: the table assumes a starting balance of $1000
7.50%
$1075
$1156
$1242
$1335
$1436
…
Slide 45
Previous Table As
A 2-D Java Array
Indexes
0
1
2
3
Row Index 3
(4th row)
4
…
0
$1050
$1103
$1158
$1216
$1276
…
1
$1055
$1113
$1174
$1239
$1307
…
2
$1060
$1124
$1191
$1262
$1338
…
Column Index 4
(5th column)
3
$1065
$1134
$1208
$1286
$1370
…
4
$1070
$1145
$1225
$1311
$1403
…
5
$1075
$1156
$1242
$1335
$1436
…

Generalize structure to two indexes: [row][column]

Each cell contains balance for a year i (row) and a
percentage rate j (column)

All indexes use zero-numbering. Hence:


table[3][4] = cell in 4th row (year = 4) and 5th column (7.50%)
table[3][4] = $1311 (shown in yellow)
Chapter 11
S.Horton/107/Ch.
6
Slide 46
Java Syntax to Create
Multi-Dimensional Arrays

Generalized syntax for an array is:
Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n];

For example, to declare a 2-D array of float named
table from the previous example:
float[][] table = new float[5][6];
• You can also break-up the declaration as:
float[][] table;
Definition
table = new float[5][];
table[0] = new table[6];
table[1] = new table[6];
table[2] = new table[6];
table[3] = new table[6];
table[4] = new table[6];
Allocation
S.Horton/107/Ch. 6
Slide 47
Processing a 2-D Array:
Nested for Loops

Arrays and for loops are a natural fit

To process all elements of an n-D array, nest n for loops


Each loop has its own counter that corresponds to an index
For example: populate a 5x6 matrix with values from 1 to 30



The “inner” loop repeats 6 times for every “outer” loop iteration
The “outer” loop repeats 5 times
The total repeats 6 x 5 = 30 times = # of cells in table
int[][] table = new int[5][6];
int row, column, index=0;
for (row = 0; row < 5; row++)
for (column = 0; column < 6; column++)
{
index++;
table[row][column] = index;
}
S.Horton/107/Ch. 6
Slide 48
Implementation of
Multi-Dimensional Arrays

Multi-dimensional arrays are implemented as arrays of arrays.

Example:
int[][] table = new int[3][4];
 table is actually a one-dimensional array of length 3
 Each element in table is an array of int with length 4

This is called “row-oriented storage”. Why is this important?

To sequentially access elements of a matrix (fastest), you need
to loop through the outer most index in the inner most loop.
0 1 2 3
0
1
2
S.Horton/107/Ch. 6
table[0] refers to the first
row in the array, which is a
one-dimensional array itself.
Slide 49
Accessing MultiDimensional Arrays

The .length variable is valid for multi-dimensional arrays, but be careful!

table.length is the number of rows of the array
table[i].length is the length of the ith row (column length)

Note: drop the outermost index in syntax


Example for table below:



table.length gives length (3) for the number of rows in the array
table[0].length gives length (4) for the length of the row (# of columns)
Can the number of columns ever vary or is table[i].length always the same?
0 1 2 3
0
1
2
S.Horton/107/Ch. 6
table[0].length
refers to the length of
the first row in the array.
Slide 50
Ragged Arrays

Ragged arrays have rows of unequal length. This is allowed in
Java!

This means that you can never assume that a table or other
multi-dimensional array have equal column lengths.

There is no special syntax, it is all in the allocation.

When is this handy? Think arrays of strings.

Example: create a 2-D String array named book with 3
entries. The first entry has length 32, the second row has length
64, and the third row has length 128:
String[][] book;
book = new String[3][];
book[0] = new String[32];
book[1] = new String[64];
book[2] = new String[128];
S.Horton/107/Ch. 6
Slide 51
Multi-Dimensional Arrays As
Parameters And Returned Values In
Methods

Methods may use, pass, and return multidimensional array parameters!

The situation is similar to 1-D arrays, but with
more brackets.

You can even pass and return parts of a multidimensional array (think individual rows).
S.Horton/107/Ch. 6
Slide 52
Example: Multi-Dimensional
Array Parameter
…
/*********************************************
* Method to output a table to the console.
*********************************************/
public static void displayTable(int[][] A)
{
int row, col;
for (row = 0; row < A.length; row++)
{
for (col = 0; col < A[row].length; col++)
System.out.print(A[row][column] + "\t");
System.out.println();
}
}
S.Horton/107/Ch. 6
Slide 53
Example: Multi-Dimensional
Array Parameter
…
/*********************************************************************
* Method to calculate compounded value. The interest rate is in
* decimal. Example 5% would be 0.05
*********************************************************************/
public static float balance(float startBalance, int years, float rate)
{
return startBalance*Math.pow(1.0+rate,(float)years);
}
S.Horton/107/Ch. 6
Slide 54
Putting It All Together: Calculate
Compounding Table From Previous
Example

Each array element in the table corresponds to the
balance for a specific number of years and a specific
interest rate (assuming a starting balance of $1000):
The
formula for computing the ending balance is:
endb(startb, years, rate) = (startb) x (1 + rate)years

Let’s put this calculation in a nice helper method
…
/*********************************************************************
* Method to calculate compounded value. The interest rate is in
* decimal. Example 5% would be 0.05
*********************************************************************/
public static float balance(float startBalance, int years, float rate)
{
return startBalance*Math.pow(1.0+rate,(float)years);
}
S.Horton/107/Ch. 6
Slide 55
Pseudocode For
Compounding Table
1. Define the table array
2. Loop through each element in table
1. Initialize starting balance to $1000
2. Compute ending balance with compound formula
3. Update table element
3. Display the table to the user
S.Horton/107/Ch. 6
Slide 56
Compounding Table Code
…
float[][] table = new float[5][6]; //Compound table
float rate;
int row, col, year;
for (row=0; row<table.length; row++)
for (col=0; col<table[row].length; col++)
{
year = row + 1;
//For years 1-5
rate = (5.0 + 0.5*col)/100.0; //Rate from 5% - 7.5%
table[row][col] = balance(1000.0,year,rate);
}
displayTable(table);
//Show user result
S.Horton/107/Ch. 6
Slide 57