logo Practice-It logo

runningTotal

Related Links:
Author: Stuart Reges (on 2014/02/13)

Write a method runningTotal that returns a new ArrayIntList that contains a running total of the original list. In other words, the i-th value in the new list should store the sum of elements 0 through i of the original list. For example, if a variable list stores the following sequence of values:

    [2, 3, 5, 4, 7, 15, 20, 7]

and the following call is made:

    ArrayIntList list2 = list.runningTotal();

Then the variable list2 should store the following sequence of values:

    [2, 5, 10, 14, 21, 36, 56, 63]

The original list should not be changed by the method. The new list should have the same capacity as the original. Remember that there is a constructor for ArrayIntList that takes a capacity as a parameter:

    // pre : capacity >= 0
    // post: constructs an empty list with the given capacity
    public ArrayIntList(int capacity)

If the original list is empty, the result should be an empty list.

You are writing a method for the ArrayIntList class discussed in lecture (handouts 3 and 5):

    public class ArrayIntList {
        private int[] elementData; // list of integers
        private int size;          // current # of elements in the list

        <methods>
    }

You are not to call any ArrayIntList methods other than a constructor to solve this problem and your method must run in O(n) time where n is the size of the list.

Write your solution to runningTotal below.

Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.