Write a program named Averages that includes a method named Average that accepts any number of numeric parameters, displays them, and displays their average. For example, if 7 and 4 were passed to the method, the output would be: 7 4 -- Average is 5.5 Test your function in your Main(). Tests will be run against Average() to determine that it works correctly when passed one, two, or three numbers, or an array of numbers. Grading When you have completed your program, click the Submit button to record your score.

Respuesta :

Answer:

In Java:

import java.util.*;

public class Averages{

public static double Average(int [] myarr, int n){

    double sum = 0;

    for(int i = 0;i<n;i++){

        System.out.print(myarr[i]+" ");

        sum+=myarr[i];     }

    System.out.println();

    return sum/n; }

public static void main(String[] args) {

  Scanner inp = new Scanner(System.in);

  System.out.print("Length of inputs: ");

  int n = inp.nextInt();

  int [] arr = new int[n];

  System.out.print("Enter inputs: ");

  for(int i = 0; i<n;i++){

      arr[i] = inp.nextInt();   }

  System.out.println("Average: "+Average(arr,n)); }}

Explanation:

The function is defined here

public static double Average(int [] myarr, int n){

Initialize sum to 0

    double sum = 0;

Iterate through the elements of the array

    for(int i = 0;i<n;i++){

Print each element followed by space

        System.out.print(myarr[i]+" ");

Add up elemente of the array

        sum+=myarr[i];     }

Print a new line

    System.out.println();

Return the average

    return sum/n; }

The main begins here

public static void main(String[] args) {

  Scanner inp = new Scanner(System.in);

Prompt the user for number of inputs

  System.out.print("Length of inputs: ");

Get the number of inputs

  int n = inp.nextInt();

Declare an array

  int [] arr = new int[n];

Get element of the array

  System.out.print("Enter inputs: ");

  for(int i = 0; i<n;i++){

      arr[i] = inp.nextInt();   }

Call the Average function

  System.out.println("Average: "+Average(arr,n)); }}

Otras preguntas