Missing Number

This program finds the missing number from a sequence.
It uses the formula for the sum of first n natural numbers.

Java Code
// Java program to find the missing number in an array
public class MissingNumber {
    public static void main(String[] args) {
        int[] nums = {3, 0, 1, 5, 2, 6, 4}; // One number from 0 to 7 is missing
        int missing = findMissingNumber(nums);
        System.out.println("The missing number is: " + missing);
    }

    public static int findMissingNumber(int[] nums) {
        int n = nums.length; // Length is 7, so numbers should be from 0 to 7 (total 8 numbers)
        
        // Total sum of numbers from 0 to n using formula n*(n+1)/2
        int expectedSum = n * (n + 1) / 2;

        // Calculate actual sum of array
        int actualSum = 0;
        for (int num : nums) {
            actualSum += num;
        }

        // Missing number = expected - actual
        return expectedSum - actualSum;
    }
}
    
Output
The missing number is: 7