1. Print and Search with arrays
2. Add and multiply the elements in an array
3. Max element in array
4. First / Last index of an element
1.1. Print the elements of an array
Here we re-visit the examples from the topic on Strings -- print an array
and search for an element in an array.
Goal: Write a method printArray(double[] numbers) that takes an array and displays
the individual elements separated by a single space.
For example:
double[] data = { 3, 6, 1, 5, 4 };
printArray(data); // displays: 3, 6, 1, 5, 4,
Here is a possible description of the method in English and its Java translations:
2. for each valid index, one at a time:
3. extract current element
4. print current element followed by a space
|
void printArray( double[] numbers )
{
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
double curValue = numbers[ index ];
System.out.print( curValue + ", " );
}
System.out.println();
}
|
Compare the similarities between the code for printing the characters of a string and the elements of an array:
void printSpelling( String phrase )
{
for ( int index = 0 ; index < phrase.length() ; index = index + 1 )
{
char curLetter = phrase.charAt( index );
System.out.print( curLetter + ", " );
}
System.out.println();
}
|
void printArray( double[] numbers )
{
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
double curValue = numbers[ index ];
System.out.print( curValue + ", " );
}
System.out.println();
}
|
1.2. Search for a value/element in an array
Goal: Write a method hasElement(numbers, value) that takes an array
and a single value and determines whether the given array contains the given value:
For example:
hasElement( new double[]{ 5, 2, 6, 1, 4 }, 1 ) should return true
hasElement( new double[]{ 5, 2, 6, 1, 4 }, 3 ) should return false
Note that:
- this is a boolean method since it effectively reports only "Yes"/"No"
- its name is phrased as a question to suggest that it is a boolean method
Here is the description of the computation process in English and its Java translation:
1. for each valid index, one at a time:
2. extract the current character
3. if the current character is a vowel:
4. report success
5. report failure
|
boolean hasElement( double[] numbers, double value )
{
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
double curValue = numbers[ index ];
if ( curValue == value )
{
return true;
}
}
return false;
}
|
Compare the similarities between the code for printing the characters of a string and the elements of an array:
boolean hasCharacter( String phrase, char letter )
{
for (int index = 0 ; index < numbers.length() ; index = index + 1)
{
char curLetter = phrase.charAt( index );
if ( curLetter == letter )
{
return true;
}
}
return false;
}
|
boolean hasElement( double[] numbers, double value )
{
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
double curValue = numbers[ index ];
if ( curValue == value )
{
return true;
}
}
return false;
}
|
2. Add / Multiply the numbers in an array
Goal: Write a method that takes an array of numbers and returns the
sum of the elements in the array.
Again we are faced with the task of traversing an array one element at a time.
This time we need an extra variable that keeps track of the overall sum so far.
This is similar to some of the earlier examples on adding the numbers in a given
sequence, but this time the sequence is stored in an array.
double addElements( double[] numbers )
{
double sum = 0;
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
sum = sum + numbers[ index ]; // OR: int curValue = numbers[ index ];
} // sum = sum + curValue;
return sum;
}
A variation of this example is to multiply all elements in the array. The only
major difference is that the initial value of the
result is 1. (If we use 0,
the multiplication will only produce 0s throughout.
Compare the two versions:
double multiplyElements( double[] numbers )
{
double product = 1;
for ( int index = 0 ; index < numbers.length ; index = index + 1 )
{
product = product * numbers[ index ];
}
return product;
}
|
double addElements(double[] numbers)
{
double sum = 0;
for ( double index = 0 ; index < numbers.length ; index = index + 1 )
{
sum = sum + numbers[ index ];
}
return sum;
}
|
3. Max/min element in array
Finding the max/min element in a collection of items is a frequently performed
task. The process of computing the max element is straightforward except for a
few subtle points.
Goal: Write a method maxElement(numbers) which takes as input an
array of numbers and computes (returns) the biggest value in the array
The idea of finding the max element is to keep a variable that stores the
max value seen so far. As we traverse the array, if the current element is
greater than the current max, we update the current max:
Here is a possible description of the method in English and its Java translations:
1. create a variable to keep track of current max
2. traverse the array one element at a time:
3. if current element > current max:
update current max
4. return current max
|
double maxElement( double[] numbers )
{
double maxValue = numbers[ 0 ];
for ( int i = 1 ; i < numbers.length ; i = i + 1 )
{
if ( numbers[ i ] > maxValue )
{
maxValue = numbers[ i ];
}
}
return max;
}
|
Notice that in the code above we:
- initialize the max with the first element; initializing with 0 does not work
if all values are negative, but the first element is a good choice -- either
it happens to be the largest element, or it will be updated later on
- since the first element (at index 0) is taken care of, the loop start at the
next element (at index 1)
- the method will not work for empty arrays, but we do not have a way right
now to take this into account -- there is no reasonable number value that
we can return, so we leave this for CS II
4. Find the first / last index of an element in an array
This is just a review from the section on Strings that illustrates the close
similarities between String and Array processing. The only difference is the
new notation to access an element at a particular index and no ()s for length.
Compare the different versions:
| First Index of Element / Character |
int getFirstIndex( double[] numbers, double value )
{
for ( int i = 0 ; i < numbers.length ; i = i + 1 )
{
double curValue = numbers[ i ];
if ( curValue == value )
{
return i;
}
}
return -1;
}
|
int getFirstIndex( String phrase, int letter )
{
for ( int i = 0 ; i < phrase.length() ; i = i + 1 )
{
char curLetter = phrase.charAt( i );
if ( curLetter == letter )
{
return i;
}
}
return -1;
}
|
| Last Index of Element / Character |
int getLastIndex( double[] numbers, double value )
{
for ( int i = numbers.length - 1 ; i >= 0 ; i = i - 1 )
{
double curValue = numbers[ i ];
if ( curValue == value )
{
return i;
}
}
return -1;
}
|
int getLastIndex( String phrase, int letter )
{
for ( int i = phrase.length() - 1 ; i >= 0 ; i = i - 1 )
{
char curLetter = phrase.charAt( i );
if ( curLetter == letter )
{
return i;
}
}
return -1;
}
|