Ask Question
29 August, 02:04

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.

+3
Answers (1)
  1. 29 August, 03:59
    0
    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;

    }

    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.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “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 ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers