java

How to Add Elements in Array in Java

In this tutorial, we are going to see two programs for calculating the sum of all the elements of an array in Java. The first program finds the sum of the elements of the specified array. The second program takes the numbers provided by the user and finds the sum of those numbers using an array.
 

Example 1: Program to Add Elements in Array
class Main {
   public static void main(String args[]){
      int[] arr = {1, 2, 3, 4, 5};
      int sum = 0;

      for( int i : arr) {
          sum = sum + i;
      }
      System.out.println("The sum of the array elements is : "+ sum);
   }
}

Output:

The sum of the array elements is : 15

 

 

Example 2: Calculate the sum of the numbers entered by the user
import java.util.Scanner;

class Main {
   public static void main(String args[]){
      Scanner scanner = new Scanner(System.in);
      int[] arr = new int[10];
      int sum = 0;
	  
      System.out.println("Enter the elements of the array: ");
      for (int i=0; i < 5; i++)
      {
    	  arr[i] = scanner.nextInt();
      }
      for( int i : arr) {
          sum = sum + i;
      }
      System.out.println("The sum of the array elements is : "+ sum);
   }
}

Output:

Enter the elements of the array: 
1
2
3
4
5
The sum of the array elements is : 15
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *