简体   繁体   中英

calculate and return the sum of all the even numbers in the 2d-array in java

This Matrix class takes a int[][] as a parameter and saves it in the instance variable.

I need to complete the sumOfEvenNumbers method to calculate and return the sum of all the even numbers in the array.

public class Matrix
{
    private int[][] matrix;

    /**
     * Gets the sum of all the even numbers in the matrix
     * @return the sum of all the even numbers
     */
    public int sumOfEvenNumbers()
    {
        int sum = 0;
        for (int[] i: array)                          
        if (i%2 == 0){ 
        sum += i;        
        }
        return sum;
         // TODO: Return the sum of all the numbers which are even
    }
}

Since you have a 2D array, you'll need to iterate through rows and columns:

int sum = 0;

for (int i=0;i<arr.length;i++)
    for (int j=0;j<arr[i].length;j++)
        if(arr[i][j] % 2 == 0)
            sum += arr[i][j];

return sum;

Alternatively, use a for-each to make this even simpler:

int sum = 0;

for (int[] innerArr : arr)
    for (int i : innerArr)
        if(i % 2 == 0)
            sum += i;

return sum;

If you are looking to apply this to a two d array, try using a normal for loop which has a column counter and a row counter, then adding up the sums. So basically a for loop inside a for loop. Likewise:

for(int col=0; col < matrix.length; col++)
{
  for(int row=0; row < matrix.length; row++)
 {
  //your code to access display[row][col]
 }
}

Your current code only supports 1 Dimensional arrays with an enhanced for loop. Enhanced for loops are great for printing output, but not for assigning/checking values - especially in multi dimensional arrays.

Using modulus and branches is expensive and I expect you will find a formula to be quite a bit faster. Try

public long sumOfEvenNumbers() {
    long sum =0;
    for (int[] arr: array)
        for(int i : arr)                          
            sum += (~i & 1) * i;        
    return sum;
}

If you have (i & 1) * i this will be 0 for even and i for odd. This would effective only add odd numbers. To flip this for even numbers, we can flip the bits of i and use (~i & 1) * i which is 0 for odd and i for even.

~i flips all the bits of i and is the same as i ^ -1 or -i - 1 or more accurately -i == ~i + 1

package Homeworks;

public class HW89SumEvenIndexEvenRow {
    public static void main(String[] args) {

        int[][] a = {
                {-5,-2,-3,7},
                {1,-5,-2,2},
                {1,-2,3,-4}
        };
        int sum=0;
        for (int i=0;i<a.length;i+=1){
            for (int j=0;j<a[i].length;j++)
                if(i%2==0 ||j%2==0) {
                    sum=sum+a[i][j];
                }
        }
        System.out.println(sum);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM