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 parameterargs
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
- Accept n numbers from command line
- Convert the strings into integers using
Interger.parseInt()
function. - 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. - Divide the sum by
args.length
. - 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