BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C++ Program to find the Missing Number

Last Updated: September 4, 2017 by Chaitanya Singh | Filed Under: C++ Programs

We are given a list of numbers in increasing order, but there is a missing number in the list. We will write a program to find that missing number.
For example, when user enters the 5 numbers in that order: 1, 2, 3, 4, 6 then the missing number is 5.

To understand this program, you should have the basic knowledge of for loop and functions.

Program

We are asking user to input the size of array which means the number of elements user wish to enter, after that user is asked to enter those elements in increasing order by missing any element. The program finds the missing element.

The logic we are using is:
Sum of n integer elements is: n(n+1)/2. Here we are missing one element which means we should replace n with n+1 so the total of elements in our case becomes: (n+1)(n+2)/2. Once we have the total, we are removing all the elements that user has entered from the total, this way the remaining value is our missing number.

#include <iostream>
using namespace std;
int findMissingNo (int arr[], int len){
   int temp;  
   temp  = ((len+1)*(len+2))/2;  
   for (int i = 0; i<len; i++)    
      temp -= arr[i];  
   return temp;
}
int main() {
   int n;   
   cout<<"Enter the size of array: "; 
   cin>>n;    int arr[n-1];  
   cout<<"Enter array elements: ";   
   for(int i=0; i<n; i++){    
      cin>>arr[i];  
   } 
   int missingNo = findMissingNo(arr,5); 
   cout<<"Missing Number is: "<<missingNo;
   return 0;
}

Output:

Enter the size of array: 5
Enter array elements: 1
2
3
5
6
Missing Number is: 4

Top Related Articles:

  1. C++ Program to Find Smallest Element in an Array
  2. C++ Program to add two numbers
  3. C++ Program to Find largest element in an array
  4. C++ Program to Find Second Smallest Element in an Array
  5. C++ Program to check whether the input number is Even or Odd

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap