Patryk Szymańczyk
Patryk Szymańczyk

Reputation: 37

Start loop from half if array is odd in java

I have a problem like in tittle, i want to make loop for for array with odd elements,

Ex. [ 5 , 5 , 3 , 7] in this way program will take 5+5 for left sum (array.lenght /2) and 3+7 for right sum. After all i want to compare them.

Problem is when the array looks like [ 5 , 5 , 3 ] in that way i cannot make array.lenght/2

And the question is what can i do?

    int rightSum = 0;
    int leftSum = 0;

    for (int i = 0; i < array.length / 2; i++) {
        leftSum += array[i];
    }
    if (array.length % 2 == 0) {
        for (int i = array.length / 2; i < array.length; i++) {
            rightSum += array[i];
        }
    } else {

    }

    return leftSum == rightSum;
}

Upvotes: 0

Views: 422

Answers (2)

WJS
WJS

Reputation: 40044

If you want, you can do it in a single loop. Simply iterate halfway thru and sum the appropriate values from left and right. If the array is of odd length, the middle value is ignored.

Note that if you change the conditional to include the middle value, it will simply be added to both side sums. So there is really no point in it.

public static boolean halfSums(int[] arr) {
    int left = 0;
    int right = 0;
    for (int i = 0; i < arr.length/2; i++) {
        left += arr[i];
        right+= arr[arr.length-i-1];
    }
    return left == right;
}

Upvotes: 1

Ismael Sarmento
Ismael Sarmento

Reputation: 894

Given your code, you can remove your if-else clause and have you loops like below (having the middle element ignored):

for (int i = 0; i < array.length / 2; i++) {
    leftSum += array[i];
}
for (int i = array.length - 1; i > array.length/2; i--) {
   rightSum += array[i];
}

If you want your middle element to be added to the left side, modify the condition on the first loop to 'i <= array.length / 2'; if you want the middle element added to the right side, modify the condition in your second loop to 'i >= array.length/2'

I just fixed your code, but there is a better way to code this. I guess you are new to coding, Patryk, so try writing some automated tests for the code and refactor, to increase its quality. Happy learning.

Upvotes: 1

Related Questions