Array Java Programs

Find the missing number in a second array

In this tutorial, you will learn how to write a Java program to find the missing number in a second array. Since we have a fixed array, we do not need any array input from the user. Just run the program and you will find the missing element in the second array that is present in the first array.

Our logic behind this program is:

We already have two array arr1 with elements 1, 2, 3, 4 and 5.Arr2 with elements 2, 3, 1, 0 and 5.We will add all the elements of arr1.Similarly for arr2 we will add it.And finally we will subtract the sum of elements of arr1 with arr2.And we will get the missing number of arr2.How will our program behave.Our program already has two array arr1 and arr2.

arr1 has 1, 2, 3, 4, 5 elements and arr2 has 2,3,1,0,5 elements.So it should print 4 in the output because 4 is missing in the second array which is in the first array.

Find missing number in second array which is in first array in Java

public class ArrayExample {
	public static void main(String[] args) {
		int sum = 0;
		int arr1[] = { 1, 2, 3, 4, 5 };
		int arr2[] = { 2, 3, 1, 0, 5 };
		int size = arr1.length;
		for (int i = 0; i < size; i++) {
			sum = sum + arr1[i] - arr2[i];
		}
		System.out.println("missing number is = " + sum);
	}
}

Output

missing number is = 4

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs