Finding missing number in a Java Array
Aug 9, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
Aug 9, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
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
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.