Given the following:
int[] ages = { 9, 41, 49 }; int sum = 0;
Which of the following are legal ways to add the elements of the array?
A. for (int i=0; i<ages.length; i++) sum += ages[i]; /*from www .java 2 s . c o m*/ B. for (int i=0; i<=ages.length; i++) sum += ages[i]; C. for (int i:ages) sum += i; D. sum += ages[int i:ages];
A, C.
A is the standard pre-5.0 way to add the elements.
B throws an exception because it loops one time too many.
C uses the enhanced for loop notation. D uses an illegal made-up notation.