Program to Find Average of Elements of an Array
- Write a program to Find Average of Elements of an Array in C
- Write a program to Find Average of Elements of an Array in C++
- Write a program to Find Average of Elements of an Array in Python
- Write a program to Find Average of Elements of an Array in PHP
- Write a program to Find Average of Elements of an Array in Java
- Write a program to Find Average of Elements of an Array in Java Script
- Write a program to Find Average of Elements of an Array in C#
Explanation:
By adding up each element in an array and dividing the amount by the number of elements, one may determine the array’s average.
Steps:
- Input the Array and Its Size:
- Take the number of elements (n) and the elements of the array as input.
- Initialize a Variable for Sum:
- Set a variable sum = 0 to store the cumulative sum of the array elements.
- Calculate the Sum of Elements:
- Use a loop to iterate through the array and add each element to sum
- Compute the Average:
- Divide sum by n to calculate the average: average = sum / n
- Output the Result:
- Print or return the calculated average.
Program to Find Average of Elements of an Array
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; // Example array int size = sizeof(arr) / sizeof(arr[0]); int sum = 0; for (int i = 0; i < size; i++) { sum += arr[i]; } float average = (float)sum / size; printf("Average of array elements: %.2f\n", average); return 0; }
#include <iostream> using namespace std; int main() { int arr[] = {10, 20, 30, 40, 50}; // Example array int size = sizeof(arr) / sizeof(arr[0]); int sum = 0; for (int i = 0; i < size; i++) { sum += arr[i]; } float average = (float)sum / size; cout << "Average of array elements: " << average << endl; return 0; }
arr = [10, 20, 30, 40, 50] # Example array average = sum(arr) / len(arr) print(f"Average of array elements: {average:.2f}")
<?php $arr = array(10, 20, 30, 40, 50); // Example array $sum = array_sum($arr); $average = $sum / count($arr); echo "Average of array elements: " . number_format($average, 2) . "\n"; ?>
public class Main { public static void main(String[] args) { int[] arr = {10, 20, 30, 40, 50}; // Example array int sum = 0; for (int element : arr) { sum += element; } double average = (double)sum / arr.length; System.out.printf("Average of array elements: %.2f\n", average); } }
const arr = [10, 20, 30, 40, 50]; // Example array const sum = arr.reduce((acc, val) => acc + val, 0); const average = sum / arr.length; console.log(`Average of array elements: ${average.toFixed(2)}`);
using System; class Program { static void Main() { int[] arr = {10, 20, 30, 40, 50}; // Example array int sum = 0; foreach (int element in arr) { sum += element; } double average = (double)sum / arr.Length; Console.WriteLine($"Average of array elements: {average:F2}"); } }