Java Program to find the Missing Number in an Array with output

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:05:03 Viewed : 580


Here is a Java program to find the missing number in an array of integers along with the expected output:

java
public class MissingNumberFinder { public static void main(String[] args) { int[] array = {1, 2, 4, 6, 3, 7, 8}; // The missing number is 5 int n = array.length + 1; // Including the missing number int expectedSum = n * (n + 1) / 2; // Sum of numbers from 1 to n int actualSum = 0; for (int num : array) { actualSum += num; } int missingNumber = expectedSum - actualSum; System.out.println("Given array:"); for (int num : array) { System.out.print(num + " "); } System.out.println(" The missing number is: " + missingNumber); } }

Expected Output:

yaml
Given array: 1 2 4 6 3 7 8 The missing number is: 5

In this program, we calculate the missing number in the array {1, 2, 4, 6, 3, 7, 8} using the same approach as before. The output displays the given array and the missing number, which is 5 in this case.

Search
Related Articles

Leave a Comment: