Java program to find the missing number in array

Write a java program to find the missing number in array.

 

package program;

public class MissingNumber {
public static void main(String[] args) {
	int[] intArray = {8,5,2,6,7,1,9,10,4};
	
	// this is lenght including missing number, we are adding 1
	int lenghtOfArray = intArray.length+1;
	int sumOfAllNumbers = (lenghtOfArray * (lenghtOfArray+1))/2;
	int sumOfGivenNumber = 0;
	for(int i=0; i < intArray.length; i++ ) {
		sumOfGivenNumber = sumOfGivenNumber + intArray[i];
	}
	
	System.out.println("Missing number is  "+(sumOfAllNumbers-sumOfGivenNumber));
	
}
}

Output is – Missing number is 3

 

Second approach –

class MissingNumber{
	
	public static void main(String[] arg) {
		int a[] = {14,3,2,4,5,6,7,8,9,10,12,1,11};
		
		Arrays.sort(a);
		for(int i=0;i<a.length-1;i++) {
			if(a[i+1]-a[i]==2) {
				System.out.println("missing no is " +(i+2));
			}
		}
		
			
			
		
		
	}
}

 

Output is –

missing no is 13