Advertisements
How to calculate sum and average in java program?
Example:-
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class AvarageTest { public static void main(String[] args) throws IOException { System.out.println("Input any No."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String data = (String) br.readLine(); int num = Integer.parseInt(data); int sum = 0; float avg = 0.0f; for (int i = 1; i <= num; i++) { sum = sum + i; } avg = sum / num; System.out.println("Sum- " + sum); System.out.println("Avg- " + avg); } }
Output
Input any Value.
Description:- In this example we are calculating sum and average of n numbers. The given code accepts the numbers from the user using BufferedReader class. Then using the for loop, we have calculated the sum of all numbers. And after dividing the sum by the total number of numbers, we have determined the average of numbers.