Ask Question
22 April, 02:51

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.

+2
Answers (1)
  1. 22 April, 03:06
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers