Java program to find the average of n numbers

This Java program finds the average on n numbers using command line arguments. The program uses a try catch statement to read the arguments form the command line. Each arguments are stored to the array a[] using a while loop. Then the program uses another while loop to calculate the sum of all the elements in the array a[] and it will be stored in the variable sum. The statement avg=sum/n; outside the while loop calculates the average and it will be displayed in the output screen.

Program



 //Java program to calculate the average of n numbers using  //command line arguments

import java.io.*; public class Average { public static void main(String s[]) throws Exception { int a[]=new int[10]; int i=0,n,sum=0,avg; n=s.length; try { while(i<n) { a[i]=Integer.parseInt(s[i]); //taking values from command line i++; } } catch(Exception e) { System.out.println("Error"); } n=i; i=0; while(i<n) { sum=sum+a[i]; i++; } avg=sum/n; System.out.println("Average is: "+avg); } }


Output


average command line n numbers java


No comments: