mathajax

Java program Sum and Average

The program is to finds sum and average or mean value from given N integers value. The input N integers are read from user via keyboard and used to calculate sum and average values.

       Example  - given inputs N=5 and integers [2 5 8 12 6]
                  sum  = 2 + 5 + 8 + 12 + 6
                  sum =  33

     average or mean = 33/5 
                     = 6.6
                                     
  

pseudocode - Sum and Average

  • Read N integers and store it into a array variable "intary"
  • set sum=0,average=0
  • For i=0 to N-1
  •   sum = sum + intary[i]
  • End For
  • average= sum / N
  • print sum,average

Java program - Sum and Average

The Java program reads N input integers from user through BufferedReader connected with keyboard and calculate sum and average value of these inputs and returns sum and average value as results of the inputs.

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AverageofNumbers {

 public static void main(String[] args) throws IOException {
            
     InputStreamReader dis =new InputStreamReader ( System.in );
     BufferedReader br =new BufferedReader(dis);
  
     System.out.println("Average of  N Numbers\n");
     System.out.println("Enter value for N");    
     String  arg1 =br.readLine();
     int N = Integer.parseInt(arg1);
     
     double sum=0;
     for( int n=0;n<N;n++ ) 
     {      
      System.out.println("Enter " + n +" value :" );          
      sum += Integer.parseInt(br.readLine());
     }
     
     System.out.println("Sum of Values : " + sum);
     System.out.println("Average of Values : " + sum/N  );
     
     
 }
}


Java Program - sum and average output


Sum and Average of  N Numbers

Enter value for N
4
Enter 0 value :
5
Enter 1 value :
8
Enter 2 value :
22
Enter 3 value :
45

Sum of Values : 80.0
Average of Values : 20.0

Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Chebyshev distance between two points

Binary 1's and 2's Complement