Site icon TestingDocs.com

Program to compute Sum and Average

Overview

In this post, we will write a simple java program to calculate the sum and average of the given numbers. We will use an integer array to hold the given numbers by the user.

IPO Chart

Input

Input to the program is the given set of numbers by the user. 

Process

The mathematical formulae are as follows:

Let n be the given set of numbers. 

 

Sum =

———————————–

 

Average = 

Output

Sum and Average of the numbers.

Tools and Environment

Eclipse IDE Setup

Some steps and instructions to create a Java application on Eclipse IDE:

https://www.testingdocs.com/create-a-new-java-project-in-eclipse/

https://www.testingdocs.com/create-java-package-in-eclipse-ide/

https://www.testingdocs.com/create-a-new-java-class-in-a-project/

https://www.testingdocs.com/run-java-project-in-eclipse/

Java Program

import java.util.Scanner;

/***********************************************************
 * SumOfArrayElements.java
 * @program : Java program to calculate sum of array elements
 * @web : www.TestingDocs.com
 * @author :
 * @version : 1.0
 ************************************************************/ 
public class SumOfArrayElements {
  public static void main(String args[]) {
    int n=0;
    int sumOfNumbers=0;
    double averageOfNumbers=0.0;
    Scanner sc = new Scanner(System.in);
    //Input of array elements from user.
    System.out.println("Enter number n:");
    n = sc.nextInt();
    int[] array= new int[n];
    for(int i=0;i<n;i++)
    {
      System.out.println("Enter number:" + (i + 1));
      array[i] = sc.nextInt();
      sumOfNumbers = sumOfNumbers + array[i];
    }

    averageOfNumbers = sumOfNumbers/ n;
    System.out.println("--------- Output of the Program --------------");
    System.out.println("Sum = " + sumOfNumbers);
    System.out.println("Average of Array elements=" + averageOfNumbers);
  }
}

 

Program Output

Save the program in the IDE. Run the program.

Right click and choose Run As >> Java Application

 

Enter number n:
5
Enter number:1
33
Enter number:2
34
Enter number:3
35
Enter number:4
36
Enter number:5
37
——— Output of the Program ————–
Sum = 175
Average of Array elements=35.0

Screenshot

Screenshot of the program.

 

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/


For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version