Ask Question
3 April, 20:00

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. 3 April, 21:33
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers