Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method to compute the average of the elements of an int array and return

ID: 3804831 • Letter: W

Question

Write a method to compute the average of the elements of an int array and return the value as a double.

The method header is: public double calculateAverage(int[] nums, int numElements)

The int array and the number of elements in the array are both passed as parameters to the method.

Note: If you want to test this method by invoking it from main, you will need to add "static" to the method header (public static double...)

Assume that:

numElements is the correct number of elements in the array

numElements is > 0

numElements could be less than the size of the array (meaning some array positions might not hold values to be included in the average)

array elements are filled sequentially starting at position 0

Explanation / Answer


import java.util.Scanner;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Surya
*/
public class Average {
  
    public static double calculateAverage(int[] nums, int numElements)
    {
        int i;//variable to traverse the array
        double average=0;//variable to calculate average
        double sum=0;//variable to find sum of all elements
        for(i=0;i<numElements;i++)//traversing all elements in list/array
        {
           sum = sum + nums[i];//calculating sum of all elements
        }
        average =sum/numElements;//calculating average
        return average ;//returning average..
    }
  
    public static void main(String argv[])//main method to test function
    {
        int n,i;//variable declaration
        Scanner sc =new Scanner(System.in);
  
        System.out.print("Enter number of elements in array:");//prompting number
        n=sc.nextInt();//reading number
      
        int a[]=new int[n];//array declaration
      
      
        System.out.println("Enter array elements:");
        for(i=1;i<=n;i++)//reading array elements
        {
      
            System.out.print("Element "+i+":");
            a[i-1]=sc.nextInt();//reading number
        }
      
        //calling function
        //and printing returned value
        System.out.println("The average of entered array is : "+calculateAverage(a,n));
    }
}

output:-

run:
Enter number of elements in array:5
Enter array elements:
Element 1:1
Element 2:2
Element 3:3
Element 4:4
Element 5:5
The average of entered array is : 3.0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote