You are on page 1of 3

 

 
AP COMPUTER SCIENCE A 

Practice Worksheet 5.3: While Loops with Arrays

1. Write a method named ​totalSum​ that receives an integer array as a parameter and returns the sum of
all of its elements. See the examples below for the expected output of ​totalSum​.

int[] stuff = {2, 4, -3, 0, 7}; totalSum(stuff) ​→ 10


int[] values = {-5, -1, -8}; totalSum(values) ​→ -14
int[] scores = {}; totalSum(scores) ​→ 0

2. Write a method named ​countTotal​ that receives a ​double​ array as a parameter and returns the
total number of elements in the array. See the examples below for the expected output of
countTotal​. You should be able to do this problem ​without a loop​.

double[] stuff = {2.3, 4.0, -1.2, 0}; countTotal(stuff) ​→ 4


double[] values = {-5.9, 73.2}; countTotal(values) ​→ 2
double[] scores = {}; countTotal(scores) ​→ 0

page 1
 
 
AP COMPUTER SCIENCE A 
3. Write a method named ​buildArray​ that receives an integer, ​n​, as a parameter and returns an integer
array of length ​n​. The value of each element in the array should be equal to its index. See the
examples below for the expected output of ​buildArray​.

buildArray (3) ​→ ​[0, 1, 2]


buildArray (5) ​→​ [0, 1, 2, 3, 4]
buildArray (0) ​→​ []

4. Write a method named ​negateArray​ that receives an integer array, ​nums​. ​negateArray​ should
return an integer array in which every element of ​nums​ has been flipped to its opposite (i.e., negated).
See the examples below for the expected output of ​negateArray​.

int[] stuff = {3, 4, 5}; negateArray (stuff) ​→​ {-3, -4, -5}
int[] nums = {0, -1, -2, -3}; negateArray (nums) ​→​ {0, 1, 2, 3}

page 2
 
 
AP COMPUTER SCIENCE A 
5. Write a method named ​getAverage​ that receives an integer array as a parameter and returns the
average of the elements in the array. See the examples below for the expected output of ​getAverage​.
You may assume the array will contain at least one element.

int[] stuff = {4, 3, 3, 2}; getAverage(stuff) ​→ 3.0


int[] values = {2, 4, 5}; getAverage(values) ​→​ 3.6666...
int[] scores = {1}; getAverage(scores) ​→​ 1.0

page 3

You might also like