Solution to
Try It Yourself: arrays

  1. public static String[] reverseIt(String[] array) {
        String[] reverse = new String[array.length];
        for (int i = 0; i < reverse.length; i++)
            reverse[i] = array[array.length - 1 - i];
        return reverse;
    }
    


  2. public static double average(double[] values) {
        double sum = 0.0;
        for (int i = 0; i < values.length; i++)
            sum += values[i];
        return sum / values.length;
    }
    


  3. for (int i = 0; i < word.length; i++) {
        if (word[i] == 'a' || word[i] == 'A')
            word[i] = '@';
        else if (word[i] == 'e' || word[i] == 'E')
            word[i] = '3';
    }
    


  4. public static boolean sameShape(int[][] matrixA, int[][] matrixB) {
          
        // check if # of rows is same 
        if (matrixA.length != matrixB.length) 
            return false; // error 
          	
        // for each row, check if # cols is same 
        for (int row = 0; row < matrixA.length; row++) 
            if (matrixA[row].length != matrixB[row]) 
                return false; // error 
          	
        return true;
    }
        


  5. int[][] sum;
    
    // first check that A and B have the same shape
    if (sameShape(A, B) { 
        // assume all rows have same number of columns 
        sum = new int[A.length, A[0].length]; 
        
        // compute A + B 
        for (int row = 0; row < A.length; row++) 
            for (int col = 0; col < A[row].length; col++) 
                sum[row][col] = A[row][col] + B[row][col];
    }
    else 
        System.out.println("Can't add matrices of different sizes");