Java program to Find missing number in array

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

The Complete logic behind to find missing number in array c is :

  • As we know that the formula (n*(n+1))/2 to add a number series.
  • where n is a number, upto you want to add.
  • Suppose you want to add number 1 to 10 then replace 10 with n and you will easily get the summation of 1 to 10.
  • Same formula will be apply for to sum 1 to 100.
  • Now have to find the missing number between 1 to 100 so for that purpose we will only subtract the sum of given number by user with the original sum from 1 to 100.
  • For example: here I am taking a small for 1 to 10. Sum of numbers from 1 to 10 is 55. and someone have entered number and their sum is 45.
  • Now when subtract 55-45 = 10 means 10 is the missing number which is not entered by user.

How our program will behave?

As we have already seen above about our logic.

This program will take a input from the user for the array size and on the basis of that user will have to insert the value.

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

And after subtraction it will give the output and that output will be the missing number.

Program to find missing number in array in Java

// Java Program to Find the Missing Number in an Array of First N Natural Numbers

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        System.out.println("=== Java Program to Find the Missing Number ===");

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of array (including missing number): ");
        int n = sc.nextInt();

        int arr[] = new int[n - 1];
        System.out.println("Enter " + (n - 1) + " array elements (from 1 to " + n + " with one missing): ");
        for (int i = 0; i < n - 1; i++) {
            arr[i] = sc.nextInt();
        }

        int totalSum = (n * (n + 1)) / 2;
        int sumArr = 0;
        for (int i = 0; i < n - 1; i++) {
            sumArr += arr[i];
        }

        int missingNumber = totalSum - sumArr;
        System.out.println("Missing number is: " + missingNumber);
    }
}

Output

=== Java Program to Find the Missing Number ===
Enter the size of array (including missing number): 5
Enter 4 array elements (from 1 to 5 with one missing): 
3
2
1
5
Missing number is: 4
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now