5. Consider the following incomplete method that adds up all of the integers in
ID: 3682780 • Letter: 5
Question
5. Consider the following incomplete method that adds up all of the integers in an array.
public static int sumArray(int[] A) {
int sum = 0;
int i = ____________________________ ;
while(i >= 0) {
sum = sum + A[i];
i--;
}
return sum;
}
What expression should be placed in the blank so that that this method will work properly?
Now consider this incomplete method that also adds up all of the integers in an array.
public static int sumArray(int[] A) {
int sum = 0;
for( __________________________________ )
sum = sum + A[i];
return sum;
}
What series of expressions should be placed in the blank so that this method will work properly?
Explanation / Answer
package com.app;
public class SumOfArrayValues {
public static void main(String[] args) {
int[] ivalues={10,20,30,50,63};
int sum=SumOfArrayValues.sumArray(ivalues);
System.out.println(sum);
}
public static int sumArray(int[] A) {
int sum = 0;
int i =(A.length)-1;
while(i >= 0) {
sum = sum + A[i];
i--;
}
return sum;
}
}
output : 173
2nd Logic:
--------------
package com.app;
public class SumOfArrayValues {
public static void main(String[] args) {
int[] ivalues={10,20,30,50,63};
int sum=SumOfArrayValues.sumArray(ivalues);
System.out.println(sum);
}
public static int sumArray(int[] A) {
int sum = 0;
for(int i=0;i<A.length;i++)
sum = sum + A[i];
return sum;
}
}
output : 173
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.