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 as the loops are pretty similar and if the even one works the others should too?
Here is my code anyway:
int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
}
else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
evenSum =evenData[evenIndex] + evenSum;
}
System.out.print("Sum of even elements: " + evenSum);
for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{
oddSum = oddData[oddIndex] + oddSum;
}
System.out.print("Sum of odd elements: " + oddSum);
for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);
You are getting same value for
evenandoddbecause you are printing the same value: –Also, your final sum is
zerobecause you are making out all the elements of your original array aszero, as you are swapping your elements with the elements inevenDataandoddData, which are zero initially.So, you are iterating your array, and assigning
0to each of your index, while adding the previous element to thenew 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: –
So, you don’t need to create extra arrays for
evenandoddnumbers.And, also your
4 loopshave now been condensed to just a single loop.