Home Tutorial Java Core Find a missing element from array

 
 

Find a missing element from array
Posted on: July 2, 2010 at 12:00 AM
In this section, you will learn how to find a missing element from the array.

Find a missing element from array

We have two arrays A and B where B consists of all the elements that are present in A but one element is missing from the array B. From these two arrays, we have to find the missing element from the second array i.e from B. For this, we have calculated the sum of elements from both the arrays and subtract them. The result will be the missing element.

Here is the code:

import java.util.*;

class CompareArrays {
	public static void main(String[] args) {
		int[] A = { 1, 2, 3, 4, 5 };
		int[] B = { 3, 1, 2, 5 };
		int i, n = 5, sum1 = 0, sum2 = 0;
		for (i = 0; i <= n - 1; i++) {
			sum1 = sum1 + A[i];
			if (i <= n - 2) {
				sum2 = sum2 + B[i];
			}
		}
		System.out.println("Missing Element is: " + (sum1 - sum2));
	}
}

Output:

Missing Element is: 4

Related Tags for Find a missing element from array:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.