Java Program to Find Average of N Numbers using Command Line Arguments

Average of N numbers java

Write a java program to find average n numbers. Write a java program to find average of n numbers using command line arguments.

Theory:

Command line arguments are passed to the main() function when the program is invoked. The parameter args and is used in main() function.

args[] is an array of strings which stores the arguments passed to the program from command line. All the arguments passed are stored as strings.

The first command line argument is always the executable program file name which can be accessed by using index 0. In Linux it is ./a.out by default.

Algorithm to find average of n numbers using command line arguments

  1. Accept n numbers from command line
  2. Convert the strings into integers using Interger.parseInt() function.
  3. Sum up the numbers starting from index 0 to value of args.length because each array has a length attribute stores the length of array.
  4. Divide the sum by args.length.
  5. Print the average of n numbers

Java program to find average of n numbers

/* Aim: Write a java program to accept n integers as command line arguments and find average */

public class MyClass {
    public static void main(String args[]) {
    
    int sum = 0;
     
    for(int i=0;i<args.length;i++)
    {
        sum +=Integer.parseInt(args[i]);
    }

    int average = sum / args.length;
    
    System.out.println("Average of " + args.length + " command line arguments is " + average);
    }
}

Output of C program:

Average of 3 command line arguments is 43.

Comments