146k views
0 votes
Write a method that returns the sum of all the elements of an array of ints that have an odd index. Please provide Java code in an easily readible format. Please provide sample output as well.

User HBomb
by
6.5k points

1 Answer

7 votes

Answer:

public int sum(ArrayList array) {

int total = 0;

for(int i=1;i<array.size();i+=2){

total += array.get(i);

}

return total;

}

Step-by-step explanation:

Step 1 define the method and variables

public int sum(ArrayList array) {

int total = 0;

Step 2 loop over the array index from 1 to array size step 2 (Keep in mind if you have step 2 beginin in 1 you loop the odd index

for(int i=1;i<array.size();i+=2){

Step 3 Acumulate the total of data with odd index

total += array.get(i);

Step 4 Return de total

return total;

Example

If you use the array [4,6,2,10]

you get as total the sum of 6 and 10 that correspond to the index 1 and 3 respective

total = 16

User Wilmer SH
by
6.1k points