public class ArraysExercises02{
Displays all of the elements of an array (of doubles) on one line
@param arr
public static void display(double[] arr){
for( int i = 0; i < arr.length; ++i){
System.out.print( arr[i] + ", ");
}
System.out.println();
}
public static void display(int[] arr){
for( int i = 0; i < arr.length; ++i){
System.out.print( arr[i] + ", ");
}
System.out.println();
}
Makes a copy of the elements in array from startIndex to endIndex (but not including endIndex) (up to the end of the array)
@param arr
@param start
@param end
@return
public static int[] subset(int[] a, int start, int end){
int subLength = end - start + 1;
int[] sub = new int[ subLength ];
for(int i = start; i <= end; ++i){
sub[i - start] = a[i];
}
return sub;
}
Returns the average value
@param arr
@return
public static double getAverage(double[] arr){
double total = 0.0;
for( int i = 0; i < arr.length; ++i){
total += arr[i];
}
return total / arr.length;
}
public static void twice(int[] a){
for( int i = 0; i < a.length; ++i){
a[i] = a[i] * 2;
}
}
Append a string to an array
@param strs
@param newItem
public static String[] append( String[] strs, String newItem){
String[] strsExpanded = new String[strs.length + 1];
for(int i = 0; i < strs.length; ++i){
strsExpanded[i] = strs[i];
}
strsExpanded[ strsExpanded.length - 1 ] = newItem;
return strsExpanded;
}
public static void main( String[] args ){
double[] milesRan = new double[365];
milesRan[0] = 3.1;
for( int i = 1; i < milesRan.length; ++i){
milesRan[i] = i;
}
double total = 0.0;
int numDays = 100;
for( int i = 0; i < numDays; ++i){
total = total + milesRan[i];
}
double averageFirst100 = total / numDays;
System.out.println("Average for the first "+numDays+" days: " + averageFirst100);
display(milesRan);
int[] values = {10, 15, 17, 21, 5, 11};
System.out.print("Before: ");
for( int i = 0; i < values.length; ++i){
System.out.print( values[i] + ", ");
}
System.out.println();
twice( values );
System.out.print("After: ");
for( int i = 0; i < values.length; ++i){
System.out.print( values[i] + ", ");
}
System.out.println();
System.out.println("Getting indices 2..4 inclusive:");
int[] newArray;
newArray = subset( values, 2, 4);
display( newArray );
String[] children = new String[ 3 ];
children[0] = "Emma";
children[1] = "Noah";
children[2] = "Olivia";
children = append( children, "Liam");
for( String child : children ){
System.out.println( child );
}
}
}