Array Java Programs

Find missing number in array

In this tutorial you will learn how to write a program to find the missing number in an integer array from 1 to 100 in the Java programming language.

The complete logic behind finding the missing number in array c is:

  1. As we know, you can add a series of numbers using the formula (n*(n+1))/2. Here, n is a number you want to add. Suppose you want to add the numbers 1 to 10, then replace 10 with n and you will easily get the sum of 1 to 10.
  2. Now we need to find the missing number between 1 and 100, so for this purpose we will simply subtract the sum of the number given by the user with the original sum of 1 to 100.
  3. Example: Here I take a small one for 1 to 10.The sum of the numbers from 1 to 10 is 55, and someone has entered a number whose sum is 45.
  4. Now if I subtract 55-45 = 10, it means that 10 is the missing number that the user did not enter.

How will our program behave?

As we have already seen above about our logic.

This program will take an input from the user for the array size and based on that the user will need to insert the value.

Then our program will add the number given by the user and then subtract it with the total sum of the given array size.

After the subtraction it will give the output and this output will be the missing number.

Find missing number in Java array

import java.util.*;

public class ArrayExample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the size of array: ");
		int n = sc.nextInt();
		int arr[] = new int[n];
		System.out.println("Enter " + (n - 1) + " array elements: ");
		for (int i = 0; i <= n - 2; i++) {
			arr[i] = sc.nextInt();
		}
		int sum = (n * (n + 1)) / 2;
		int sumArr = 0;
		for (int i = 0; i <= n - 2; i++) {
			sumArr = sumArr + arr[i];
		}
		int missingNumber = sum - sumArr;
		System.out.println("Missing number is : " + missingNumber);
	}
}  

Output

Enter the size of array: 
5
Enter 4 array elements: 
2
3
4
5
Missing number is : 1

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs