-1

Which code snippet calculates the sum of all the elements in even positions in an array?

a) int sum = 0;
for (int i = 1; < values.length; i+=2)
{
sum++;
}

b) int sum = 0
for (int i = 0; i < values.length; i++)
{
sum++;
}

c) int sum = 0;
for (int i = 0; i < values.lengthl; i++)
{
sum +=values [i];
}

d) int sum = 0;
for (int i = 0; i < values.length; i + 2)
{
sum +=values [i];
}

are any of these correct? because for my answer I got

int sum = 0;
for (int i = 0; i < values.length; i += 2)
{
sum +=values [i];
}

is my answer correct? or is it one of the multiple choices?

6
  • 1
    What's the difference between your answer and answer D? Commented Mar 21, 2015 at 14:46
  • my answer is "values.length; i +=2" for d its "values.length; i + 2) Commented Mar 21, 2015 at 14:51
  • Ah, I see. Are you sure that isn't a typo? Commented Mar 21, 2015 at 14:51
  • 1
    Why don't you run each in a unit test and see which gives the correct answer Commented Mar 21, 2015 at 14:55
  • yeah, my answer is correct right? Commented Mar 21, 2015 at 14:56

3 Answers 3

1

None of these answers appear to answer the question. Here is a code snippet which will compute the sum of all even elements of array values.

int sum = 0;
for (int i = 1; i < values.length; i = i + 2) {
    sum +=values [i];
}

You have to increment the loop variable i by 2 in order to sum only even elements. Also note that I assume the first even position is the second position in the array, which is values[1].

Sign up to request clarification or add additional context in comments.

Comments

0

A small correction you are using array in your code. ArrayList is different from Array. ArrayList doesn't have a length property, it's the property of an Array. I think the answer added by Tim Biegeieisen is correct for an array.

Similary, You can do the same thing for a array list like this -

int count=0;
int sum=0;
for(Integer i : values){
   if(count%2==0){
      sum = sum+i;
   }
   count++;
}
System.out.println(sum);  

And here values is an ArrayList of Integer. Note you can not put int or any other primitive type in ArrayList. So you may declare your ArrayList used here (that is values) like -

List<Integer> values = new ArrayList<Integer>();

Hope it will Help.
Thanks.

Comments

0

A and B don't add elements of the array to sum; B and C process all elements. So if any of them are correct, it must be D. But since D does not change i, it cannot be right, either.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.