Sum of Two Arrays in Java

In this article, you will see the Sum of two arrays in Java. Here, we will take two integer arrays and store the sum of both arrays into a 3rd integer array.

Example#1. Sum of two arrays in Java

package com.javacodepoint.array;

public class SumOfTwoArray {

	public static void main(String[] args) {

		// 1st Array
		int arr1[] = { 4, 5, 1, 6, 4, 15 };

		// 2nd Array
		int arr2[] = { 3, 5, 6, 1, 9, 6 };

		// 3rd Array to store the Sum
		int arr3[] = new int[arr1.length];

		// Adding arr1 and arr2 and storing into arr3
		for (int i = 0; i < arr1.length; i++) {
			arr3[i] = arr1[i] + arr2[i];
		}

		// Print the arr3 elements
		for (int i = 0; i < arr3.length; i++) {
			System.out.print(arr3[i] + " ");
		}

	}

}

OUTPUT:

7 10 7 7 13 21

Example#2. Addition of two arrays in Java using Scanner

In this example, we will read the array elements from the users using the Scanner java class. Let’s see the java code below:

package com.javacodepoint.array;

import java.util.Scanner;

public class SumOfTwoArrayExample2 {

	public static void main(String[] args) {

		// Creating scanner object for reading user inputs
		Scanner sc = new Scanner(System.in);

		// Read the size of the Array
		System.out.println("Enter the size of the Array: ");
		int n = sc.nextInt();

		// Declare the arr1 & arr2 of given size
		int arr1[] = new int[n];
		int arr2[] = new int[n];

		// Reading the arr1 values
		System.out.println("Enter " + n + " element(s) of the Array1: ");
		for (int i = 0; i < n; i++) {
			arr1[i] = sc.nextInt();
		}

		// Reading the arr2 values
		System.out.println("Enter " + n + " element(s) of the Array2: ");
		for (int i = 0; i < n; i++) {
			arr2[i] = sc.nextInt();
		}

		// 3rd Array to store the Sum
		int arr3[] = new int[arr1.length];

		// Adding arr1 and arr2 and storing into arr3
		for (int i = 0; i < arr1.length; i++) {
			arr3[i] = arr1[i] + arr2[i];
		}

		// Print the arr3 elements
		for (int i = 0; i < arr3.length; i++) {
			System.out.print(arr3[i] + " ");
		}

	}

}

OUTPUT:

Enter the size of the Array:
5
Enter 5 element(s) of the Array1:
1
2
3
4
5
Enter 5 element(s) of the Array2:
1
2
3
4
5
2 4 6 8 10

See also:
Java Program to Merge Two Arrays.
Java Program to Calculate Average Using Array.

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

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