osama
osama

Reputation: 33

Function takes a martix (2d array) and prints the max number of the even numbers in each line

I am defining a function to accept a matrix (2d array), for example x[][]; and the function should print the biggest even number in each line

public static void biggestEvenNumOfEachLine(int x[][]){
    int even,t=0,max;
    int arr[] = new int [x.length];
    for(int i = 0; i < x.length;i++){
        for(int j = 0; j < x[i].length;j++,t++){
            if(x[i][j] % 2 == 0){
                even = x[i][j];
                arr[j] = even;
            }   
        }
    }
}

What am I missing?

Upvotes: 3

Views: 66

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

I would start by finding the biggest even number in a single line array. Start with the smallest possible value, and then iterate the array. Test for even, and then set the max (and then return it). Something like,

private static int biggestEvenNum(int[] x) {
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < x.length; i++) {
        if (x[i] % 2 == 0) {
            max = Math.max(max, x[i]);
        }
    }
    return max;
}

But, in Java 8+, I would prefer to filter for even values and get the max like

private static int biggestEvenNum(int[] x) {
    return IntStream.of(x).filter(v -> v % 2 == 0).max().getAsInt();
}

Then your method is as simple as iterating the line(s) in your matrix, printing the result. Like,

public static void biggestEvenNumOfEachLine(int[][] x) {
    for (int[] line : x) {
        System.out.println(biggestEvenNum(line));
    }
}

Upvotes: 2

hal
hal

Reputation: 841

public static void biggestEvenNumOfEachLine(int x[][])
{
    int arr[] = new int [x.length];

    for(int i = 0; i < x.length;i++)
        for(int j = 0; j < x[i].length;j++)
            if(x[i][j] % 2 == 0 && x[i][j] > arr[i]){
                arr[i] = x[i][j];
                System.out.println(arr[i]);
            }
}

This will work but if there is no even number at particular line then corresponding number to that line will be zero.

Upvotes: 0

Related Questions