SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Implementing A Collection Class
Exercise:
Exercises
Question:4 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the ArrayIntList class from this chapter.

Write a method called runningTotal that returns a new ArrayIntList that contains a running total of the original list. In other words, the ith value in the new list should store the sum of elements 0 through i of the original list.

For example, given a variable list that stores [2, 3, 5, 4, 7, 15, 20, 7], consider what happens when the following call is made:

ArrayIntList list2 = list.runningTotal();

The variable list2 should store [2, 5, 10, 14, 21, 36, 56, 63] . The original list should not be changed by the method. If the original list is empty, the result should be an empty list. The new list should have the same capacity as the original. Remember that there is a list constructor that accepts a capacity as a parameter.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of runningTotal method:

	public ArrayIntList runningTotal()
	{
		ArrayIntList newList = new ArrayIntList(size);
		int total = 0;
		
		for(int i = 0; i < size; i++)
		{
			total = total + elementData[i];			
			newList.add(total);			
		}
		
		return newList;
	}
0 0

Discussions

Post the discussion to improve the above solution.