The problem im getting is that with oddSum the value outputted is the same as evenSum, and the value for sum of all elements is 0.
I cant quite see where im going wrong
You are getting same value for even
and odd
because you are printing the same value: -
System.out.print("Sum of odd elements: " + evenSum);
Also, your final sum is zero
because you are making out all the elements of your original array as zero
, as you are swapping your elements with the elements in evenData
and oddData
, which are zero initially.
int temp = data[index];
data[index] = evenData[index]; // This code assigns a value 0 to current index.
evenData[index] = temp;
So, you are iterating your array, and assigning 0
to each of your index, while adding the previous element to the new array
.
I would say that you are needlessly using 2 extra array and 3 extra loops. Why not just create a sum in the place where you are iterating your original array?
In fact, all your sums can be computed in a single loop: -
for(int index = 0; index < data.length; index++)
{
sum += data[index];
if (data[index] % 2 == 0)
{
// int temp = data[index];
// data[index] = evenData[index];
// evenData[index] = temp;
evenSum += data[index];
}
else
{
// int temp = data[index];
// data[index] = oddData[index];
// oddData[index] = temp;
oddSum += data[index];
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
System.out.println("Total Sum: " + sum);
So, you don't need to create extra arrays for even
and odd
numbers.
And, also your 4 loops
have now been condensed to just a single loop.