Write a program to find a missing number in an array


This program finds the missing number in an array of integers. It assumes that the array is sorted and contains all integers from 1 to n, where n is the length of the array minus 1.

The program first initializes the array num with the integers 1, 2, 4, 5, 6, 7. It then calculates the sum of integers from 1 to n using the formula res = n * ((n + 1) / 2) . Here, n is the length of the array minus 1. For example, if the length of the array is 6, then n is 5. The formula calculates the sum of integers from 1 to 5, which is 15.

Next, the program calculates the sum of all the integers in the array num using a for-each loop. It initializes a variable num_sum to 0, and then adds each integer in num to num_sum.

Finally, the program subtracts the sum of integers in num from the sum of integers from 1 to n. The result is the missing number in the array.

Source Code

import java.util.*;
public class Array_Missing_Number
{
	public static void main(String[] args)
	{
		int len;
		int[] num = new int[]{1,2,4,5,6,7};
		len = 7;
		int res = len * ((len + 1) / 2);
		int num_sum = 0;		
		for (int i: num)
		{
			num_sum += i;
		}
	        System.out.println("Missing Array Number is "+(res - num_sum));
	}
 }
 

Output

Missing Array Number is 3

Example Programs