logo CodeStepByStep logo

evenSum

Related Links:

Write a method evenSum that returns the sum of the values in even indices in a list of integers. Assume we are using a zero-based indexing where the first value in the list has index 0, the second value has index 1, and so on. The values in which we are interested in are the ones with even indices (the value at index 0, the value at index 2, the value at index 4, and so on). For example, if a variable list stores the following sequence of values:

[1, 18, 2, 7, 39, 8, 40, 7]

Then the call of list.evenSum(); should return the value 82 (1 + 2 + 39 + 40). Notice that what is important is the position of the numbers (index 0, index 2, index 4, etc.), not whether the numbers themselves are even. If the list is empty, your method should return a sum of 0.

Assume that we are adding this method to the LinkedIntList class as shown below. You may not call any other methods of the class to solve this problem and your method cannot change the contents of the list.

    public class LinkedIntList {
        private ListNode front;
        ...
    }
    
    public class ListNode {
        public int data;
        public ListNode next;
        ...
    }
Partial class: Write code that will become part of an existing class as described. You do not need to write the complete class, just the portion described in the exercise.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.