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
import java.util.*;
public class Main {
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: