In this section, we will see various variations on how to write this program.In Example 1, we will be taking array input in a predefined fashion i.e. we will be assigning elements to array pre -pre-compilation.In Example 2 we will be taking user defined array and performing operations to it.
Program to Calculate Sum and Average of Array Elements | Example 1
Algorithm:
- Start
- Initialize an array.
- int array[]={array elements};
- Define variable sum=0 to calculate array sum.
- initialize for loop
- for (int i=0;i<array.length;i++)//loop till array length.
- Calculate sum=sum+array[i].
- print Array sum.
- Calculate average=sum/array.length;
- print Array average.
- end
/*
Java Program to find Sum and Average of array Elements */
import java.util.*;
public class arrayoperations
{
public static(String args[]){
int array[]={10,20,30,40,50,60};// you can define double array too
int sum=0;
for(int i=0;i<array.length;i++)
{
/*
This logic is used for calculating sum of array elements*/
sum=sum + array[i];
}
System.out.println("Sum of Array Elements are:"+sum);
double average=(sum/arr.length);//simple average formula
System.out.format("Average of Array Elements is" +average);
}
}
Output:
Sum of Array Elements are:210
Average of Array Elements is: 35.000
Program to Calculate Sum and Average of Array elements | Example 2
Algorithm:
- Start
- define int size.//size for an array
- Initialize an array.
- Scanner sc=new Scanner(System.in).
- size=sc.nextInt();
- int array[size]={array elements};
- Define variable sum=0 to calculate array sum.
- initialize for loop for
- (int i=0;i<array.length;i++)//loop till array length.
- array[i]=sc.nextInt();
- Calculate sum=sum+array[i].
- print Array sum.
- Calculate average=sum/array.length;
- print Array average.
- end
/*
Java Program to find Sum and Average of array Elements */
import java.util.*;
public class arrayoperations
{
public static void main(String arg[]){
int size;
System.out.println("Enter the Size or Array");
Scanner sc= new Scanner(System.in);
size=sc.nextInt();
int array[]=new int[size];// you can define double array too
int sum=0;
for(int i=0;i<array.length;i++)
{
/*
This logic is used for calculating sum of array elements*/
array[i]=sc.nextInt();
sum=sum + array[i];
}
System.out.println("Sum of Array Elements are:"+sum);
double average=(sum/array.length);//simple average formula
System.out.format("Average of Array Elements is" +average);
}
}
Output:
Enter the Size or Array
5
Enter Elements in Array
10 20 30 40 50
Sum of Array Elements are:150
Average of Array Elements is30.0