Author Topic: Java - Sum, Average, Min and Max for N numbers  (Read 1440 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Java - Sum, Average, Min and Max for N numbers
« on: December 02, 2011, 02:09:47 pm »
Could you please help me out in C# that accepts N numbers as input and compute the following values:

1) Sum
2) Average
3) Minimum
4) Maximum

Code: (Java)
//Source Code Listing


import java.lang.*;
import java.util.*;
import java.io.*;
 
 
class MinMaxAvgSum
{
      public static String ReadString()
      {
           try
           {
                 InputStreamReader input = new InputStreamReader(System.in);
                 BufferedReader reader = new BufferedReader(input);
                 return reader.readLine();
           }
           catch (Exception e)
           {

                 e.printStackTrace();
                 return "";
           }
      }


      public static int ReadInteger()
      {
           try
           {
                 InputStreamReader input = new InputStreamReader(System.in);
                 BufferedReader reader = new BufferedReader(input);
                 return Integer.parseInt(reader.readLine());
           }
           catch (Exception e)
           {

                 e.printStackTrace();
                 return 0;
           }
      }
      
      
 
      public static void main(String[] args)
      {      
         System.out.println("Enter the total numbers:");
         int n = ReadInteger();
         int[] arrNumbers = new int[n];

         for (int i = 0; i < n; i++)
         {
            System.out.format("Enter %d No.: ", i + 1);
            arrNumbers[i] = ReadInteger();
         }

         int min = arrNumbers[0];
         int max = arrNumbers[0];
         int sum = 0;
         double average = 0;
         for (int i = 0; i < n; i++)
         {
            sum += arrNumbers[i];
            if (min > arrNumbers[i])
               min = arrNumbers[i];
            if (max < arrNumbers[i])
               max = arrNumbers[i];
         }
         average = (double)sum / n;

         
         System.out.format("\nSum\t: %d", sum);
         System.out.format("\nAverage\t: %.2f", average);
         System.out.format("\nMin\t: %d", min);
         System.out.format("\nMax\t: %d", max);
      }
}


/***
The output is given below:
Enter the total numbers:5
Enter 1 No.: 100
Enter 2 No.: 200
Enter 3 No.: 101
Enter 4 No.: 201
Enter 5 No.: 501
 
Sum     : 1103
Average : 220.60
Min     : 100
Max     : 501
Press any key to continue . . .
 
***/

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1