479,384 views
10 votes
10 votes
The divBySum method is intended to return the sum ofall the elements in the int arrayparameter arr that are divisible by the intparameter num. Consider the following examples, in whichthe array arrcontains {4, 1, 3, 6, 2, 9}.The call divBySum(arr, 3) will return 18,which is the sum of 3, 6, and 9,since those are the only integers in arr that aredivisible by 3.The call divBySum(arr, 5) will return 0,since none of the integers in arr are divisibleby 5.Complete the divBySum method using anenhanced for loop. Assume that arr isproperly declared and initialized. The method must use anenhanced for loop to earn full credit./** Returns the sum of all integers inarr that are divisible by num* Precondition: num > 0*/public static int divBySum(int[] arr, int num)

User Iulian David
by
2.6k points

1 Answer

18 votes
18 votes

Answer:

Step-by-step explanation:

The following program is written in Java and creates the divBySum method using a enhanced for loop. In the picture attached below I have provided an example of the output given if called using the array provided in the question and a divisible parameter of 3.

public static int divBySum(int[] arr, int num) {

int sum = 0;

for (int x : arr) {

if ((x % num) == 0) {

sum += x;

}

}

return sum;

}

The divBySum method is intended to return the sum ofall the elements in the int arrayparameter-example-1
User Fery Kaszoni
by
2.5k points