Find array elements that are greater than average

Given an array of numbers, print all those elements that are greater than average.

Examples:

Input : 5, 4, 6, 9, 10
Output : 9 10
Explanation:
avg = 5 + 4 + 6 + 9 + 10 / 5;
avg = 34 / 5
avg = 6.8
Elements greater than 6.8 are 9 and
10

Input : 1, 2, 4, 0, 5
Output : 4 5


1) Find average of elements.
2) Traverse array again and print elements that are greater than average,

C++

// A C++ program to print elements which are 
// greater than avg of array
#include <iostream>
using namespace std;

// Print array elements greater than average
void printAboveAvg(int arr[], int n)
{
    // Find average
    double avg = 0;
    for (int i = 0; i < n; i++) 
        avg += arr[i];    
    avg = avg / n;

    // Print elements greater than average
    for (int i = 0; i < n; i++) 
        if (arr[i] > avg) 
            cout << arr[i] << " ";
}

// Driver program 
int main()
{
    int arr[] = { 5, 4, 6, 9, 10 };
    int a = sizeof(arr) / sizeof(arr[0]);
    printAboveAvg(arr, a);
    return 0;
}

Python3

# python program to print elements
# which are greater than avg of
# array

# Print array elements greater
# than average
def printAboveAvg(arr, a):

    # Find average
    avg = 0
    for i in range(a):
        avg = avg + arr[i]
        
    avg = avg // a

    # Print elements greater than
    # average
    for i in range(a):
        if arr[i] > avg:
            print(arr[i], end = " ")

# Driver Program
arr = [5, 4, 6, 9, 10]
a = len(arr)
printAboveAvg(arr, a)

# This code is contributed 
# by Shrikant13.
Output:

9 10




Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.