Java

Finding missing number in a Java Array

In this particular example, we are going to find the missing number from an array of 1-100 using a simple technique.

Whole scenario is, we have an array containing numbers between 1 to 100 with one particular number being missed out. We will find that missing number using following code.

Steps are pretty straightforward

  1. Take the sum of 1-100
  2. Take the sum of array elements
  3. Difference between the sum of 1-100 and sum of array element is your missing number.
class FindingMissingNumberInArray
{
    public static void main(String[] args)
    {

        int[] arrayWithMissingNumber=new int[100];

        for(int i=0;i<100;i++)
        {
            if(i==37)
            {
                arrayWithMissingNumber[i]=0;
            }
            else
            {
                arrayWithMissingNumber[i]=i+1;
            }
        }


        int sum=0;
        for(int i=1;i<=100;i++)
        {
            sum=sum+i;
        }

        System.out.println("Sum of 1-100 is:"+sum);

        int sumOfArray=0;


        for(int i=0;i<arrayWithMissingNumber.length;i++)
        {
            sumOfArray=sumOfArray+arrayWithMissingNumber[i];
        }


        System.out.println("Sum of array is:"+sumOfArray);


        int missingNumber=sum-sumOfArray;

        System.out.println("Missing Number in the array was:"+missingNumber);
    }
    
}

You can see the execution of the same in the following video.

Related Posts

Table Of Contents

;