Computing sum of values in array

后端 未结 2 1257
南旧
南旧 2021-01-24 05:23

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

2条回答
  •  清酒与你
    2021-01-24 06:07

    int temp = data[index]; 
    data[index] = evenData[index]; 
    evenData[index] = temp; 
    

    Looking at your above lines, evenDate is empty and in second line you are setting your data array to be empty. You are repeating the same mistake in oddDate line as well.

    Why don't you use just try the following?

        for(int index = 0; index < data.length; index++)
        { 
            if (data[index] % 2 == 0) { 
                int temp = data[index]; 
                evenData[index] = temp;
    
            } else { 
                int temp = data[index]; 
                oddData[index] = temp; } 
            } 
        }
    
        for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++) 
        { 
            //since length of all 3 data,even, odd arrays are the same
            //you can put both sum operation in one for loop
    
            evenSum = evenData[evenIndex] + evenSum; 
            oddSum = oddData[evenIndex] + oddSum; 
            sum = data[evenIndex] + sum;  
        }
    
        System.out.print("Sum of even elements: " + evenSum); 
        //you have put evenSum for below odeUm printing in ur code
        System.out.print("Sum of odd elements: " + oddSum); 
        System.out.print("Sum of all elements: " + sum); 
    

提交回复
热议问题