public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 6, 7, 8, 9, 10}; // array with missing number
int n = arr.length + 1; // length of original array
int sum = n * (n + 1) / 2; // sum of integers from 1 to n
for (int i = 0; i < arr.length; i++) {
sum -= arr[i]; // subtract each element in the array from the sum
}
System.out.println("The missing number is: " + sum); // output the missing number
}
}
This program calculates the sum of integers from 1 to n (where n is the length of the original array plus one), and then subtracts each element in the array from the sum. The result is the missing number in the array. In the example array above, the missing number is 5.
The code given below shows how to find the missing number in an array of integers:
class missingNum
{
public static void main(String[] args)
{
int[] nums = { 1, 2, 3, 5, 4, 8, 6}; // Declare and initialize and an integer array.
int n = nums.length; // Store length of the integer array
int sum = ((n + 1) * (n + 2)) / 2; // Sum of n numbers
for (int i = 0; i < n; i++)
sum -= nums[i]; // Subtracts each element from sum
System.out.println("The missing number is " + sum + ".");
}
}
OUTPUT:
The missing number is 7.
We can obtain the missing element by subtracting the sum of all elements from the sum of the first n natural numbers, where n is the largest number in the array.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
This program calculates the sum of integers from 1 to n (where n is the length of the original array plus one), and then subtracts each element in the array from the sum. The result is the missing number in the array. In the example array above, the missing number is 5.
The code given below shows how to find the missing number in an array of integers:
We can obtain the missing element by subtracting the sum of all elements from the sum of the first n natural numbers, where n is the largest number in the array.