Reputation: 7
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?
Upvotes: -1
Views: 59
Reputation: 49920
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.
Upvotes: 0
Reputation: 11173
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.
Upvotes: 0
Reputation: 522741
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]
.
Upvotes: 1