Problem Statement: Given an array, we have to find the average of all the elements in the array.
Examples:
Example 1: Input: N = 5, array[] = {1,2,3,4,5} Output: 3 Explanation: Average is the sum of all the elements divided by number of elements.Therefore (1+2+3+4+5)/5 = 3. Example 2: Input: N=6, array[] = {1,2,1,1,5,1} Output: 1.8 Explanation: Average is the sum of all the elements divided by number of elements.Therefore (1+2+1+1+5+1)/6 = 1.8
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Approach:
- Using for loop traverse through the array and while traversing maintain a variable for storing sum of the elements in the array.
- After completing the traversal simply divide the sum by no. of elements in the array.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main() {
int n = 5;
int arr[] = {1, 2, 3, 4, 5};
double sum = 0;
for (int i = 0; i < n; i++) {
sum += (double)arr[i];
}
double average = sum / n;
cout << "The average is "<<average;
}
Output:
The average is 3
Time Complexity: O(n) As we are traversing the array once.
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
int n = 5;
int arr[] = {1,2,3,4,5};
//using double as average can be in decimal.
double sum = 0;
for (int i = 0; i < n; i++) {
sum += (double) arr[i];
}
double average = sum / n;
System.out.println("The average is "+average);
}
}
Output:
The average is 3.0
Time Complexity: O(n) As we are traversing the array once.
Space Complexity: O(1).
Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article