• In the first method

    Use the formula n(n+1)/2 that counts the number of elements and then need to subtract from the elements in the array.

  • What are the different ways to find missing numbers in a sorted array without any inbuilt functions using C#?



    There are three methods as written below −

    • In the first method

      Use the formula n(n+1)/2 that counts the number of elements and then need to subtract from the elements in the array.

    • In the second method

      Create a new array and traverse through the entire array and make the number false whichever is found.

    • In the third method

      Use Xor operation. which gives the missing number.

    Example

     Live Demo

    using System;
    namespace ConsoleApplication{
       public class Arrays{
          public int MissingNumber1(int[] arr){
             int totalcount = 0;
             for (int i = 0; i < arr.Length; i++){
                totalcount += arr[i];
             }
             int count = (arr.Length * (arr.Length + 1)) / 2;
             return count - totalcount;
          }
          public int MissingNumber2(int[] arr){
             bool[] tempArray = new bool[arr.Length + 1];
             int element = -1;
             for (int i = 0; i < arr.Length; i++){
                int index = arr[i];
                tempArray[index] = true;
             }
             for (int i = 0; i < tempArray.Length; i++){
                if (tempArray[i] == false){
                   element = i;
                   break;
                }
             }
             return element;
          }
          public int MissingNumber3(int[] arr){
             int result = 1;
             for (int i = 0; i < arr.Length; i++){
                result = result ^ arr[i];
             }
             return result;
          }
       }
       class Program{
          static void Main(string[] args){
             Arrays a = new Arrays();
             int[] arr = { 0, 1, 3, 4, 5 };
             Console.WriteLine(a.MissingNumber1(arr));
             Console.WriteLine(a.MissingNumber2(arr));
             Console.WriteLine(a.MissingNumber3(arr));
             Console.ReadLine();
          }
       }
    }

    Output

    2
    2
    2
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements