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
- JDK
- Windows 10 OS
Eclipse IDE Setup
Some steps and instructions to create a Java application on Eclipse IDE:
- Create Java Project in Eclipse
https://www.testingdocs.com/create-a-new-java-project-in-eclipse/
- Create Java Package in Eclipse
https://www.testingdocs.com/create-java-package-in-eclipse-ide/
- Create Java Class in Eclipse
https://www.testingdocs.com/create-a-new-java-class-in-a-project/
- Run Java Project in Eclipse
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 :