Google News
logo
C++ Program to Find the Missing Number
In the following example of C++ program to find the missing number in an array of integers :
Program :
#include <iostream>

int main() {
    const int SIZE = 10;
    int arr[SIZE] = {1, 2, 3, 4, 5, 6, 8, 9, 10}; // an example array
    int sum = 0;
    for (int i = 0; i < SIZE - 1; i++) {
        sum += arr[i];
    }
    int expected_sum = (SIZE * (SIZE + 1)) / 2; // sum of all integers from 1 to SIZE
    int missing_number = expected_sum - sum;
    std::cout << "The missing number is " << missing_number << std::endl;
    return 0;
}
Output :
The missing number is 7
* This program assumes that the array contains integers from 1 to SIZE with one number missing. In this example, the missing number is 7.

* The program first calculates the sum of all the integers in the array, except for the missing number. It does this using a for loop to iterate over each element of the array.

* Next, the program calculates the expected sum of all the integers from 1 to SIZE using the formula (SIZE * (SIZE + 1)) / 2. This is the sum that would be obtained if no number were missing from the array.

* The missing number is then calculated by subtracting the actual sum from the expected sum.

* Finally, the program outputs the missing number to the console using std::cout.