197k views
3 votes
Write a function double average(int arr[] , int n), that returns the average of the even elements of the array. If the array has no even elements, throw an integer-based exception containing the value 0. The number of elements in the array is specified by the parameter n.

1 Answer

6 votes

Answer:

double average(int arr[], int n){

int evenElementCount = 0;

double sum = 0;

for( int i = 0; i < n; i++) {

if( arr [ i ] % 2 == 0 && arr [ i ] != 0 ){

evenElementCount += 1;

sum+=arr[i];

}

}

if(evenElementCount == 0)

throw 0;

return sum/evenElementCount;

}

Step-by-step explanation:

The Method called average takes in an array and number of elements, it loops through the array using a for-loop to find all the even elements in the array, it stores the number of even elements in a variable named evenElementCount, it throws an integer-based exception if the evenElementCount variable is 0, returns average of even elements if the evenElementCount variable is not 0.

User MaM
by
5.4k points