Tutorials

Java Array


Array Sum Program


In this chapter, our task is to write a simple java program:

  • to declare an array
  • assign values
  • calculate sum of all the elements in array
  • calculate average of all the elements in array
  • print sum and average

Java Program to find sum and average of the array.

package array;

public class ArraySum {

	public static void main(String[] args) {
		int[] arr = {13, 17, 18, 23, 35, 65};
		int sum = 0;

		//sum of elements
		for(int i=0; i<arr.length; i++){
			sum = sum + arr[i];
		}
		System.out.println("sum of array elements: "+ sum);
		
		float average = (float)sum/arr.length;
		System.out.println("average of array elements: "+ average);

	}

}

OUTPUT:

sum of array elements: 171
average of array elements: 28.5

 

Points to Note

  • We can also declare and assign values as shown in the above program. In previous chapter we saw different procedure. You can use any way depending on your wish.
  • variable 'sum' is assigned value 0 and declared outside loop so that it can be used outside loop as well. We have used the value to calculate average outside the loop. If we had declared it inside for loop then its usage would have been restricted to within the loop only.
  • ¬†average of array is typecasted as (float) to recieve the accurate value 28.5. If you remove the typecasting then also program would execute fine but output for average would then be 28.0


Please Share this page
Views : 62
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!