Write a java Program which will find the missing number in an Array |EasyCoding45

Write a Java program that will find the missing number in an Array.

You are given an array containing n distinct numbers taken from the range 1 to n+1. This means there is one number missing from the sequence.


public class MissingNumber {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 4, 6, 3, 7, 8};
        int missing1 = findMissingNumber(array1);
        System.out.println("Missing number in array1: " + missing1);  // Output: 5

        int[] array2 = {1, 3, 5, 4, 6, 8, 7, 9, 11};
        int missing2 = findMissingNumber(array2);
        System.out.println("Missing number in array2: " + missing2);  // Output: 2
    }

    static int findMissingNumber(int[] nums) {
        int n = nums.length + 1;
        int expectedSum = n * (n + 1) / 2;
        int actualSum = 0;

        for (int num : nums) {
            actualSum += num;
        }

        return expectedSum - actualSum;
    }
}

Output :


https://easycoding45.blogspot.com/2023/11/write-java-program-which-will-find.html


Comments