Find missing number between 1 to N in array in C#

Find missing number in the sequence in c#- Learn how to find the missing number among the sequence of numbers from 1 to n with example Programs.

For Example following are the numbers from 1 to 6 as 1,2,3,5,6.
The missing number in the above sequence is 4.

Input

1,2,3,5,6

Output

Missing Number : 4

How to calculate missing number?

Solution:
total numbers=5
sum of 6 numbers from 1 to 6 =6*(6+1)/2;
=21;

sum of the Numbers in the sequence =17.

missing Number=sum of 6 numbers-sum of the Numbers in the sequence
= 21-17 =4

Method 1:(Using Mathematical formula)

Algorithm:

step1: calculate sum of Numbers : n*(n+1)/2 – say as x
step2: calculate sum of numbers in the sequence – say as y
step3: subtract x-y to get the missing Number.

C# Programming Example

using System;
class Find_Missing_Number
    {
        static void Main(string[] args)
        {
            //array to find the missing number between 1 and 10
            // Simplicity, We will take number 1 to 10 i where Number 5 is missing in the sequence.
            int[] arr = { 1, 2, 3, 4, 6, 7, 8, 9, 10 };

            int missingNumber,Totalsum;
            // Accoreding to series rule, calculating sum of total numbers upto 10
            //sum of first n natutal numbers=n*(n+1)/2
            Totalsum = (arr.Length + 1) * (arr.Length + 2) / 2;

            // Missing number is calculating.
            foreach (int item in arr)
            {
                Totalsum = Totalsum - item;
            }
            missingNumber = Totalsum;

            Console.WriteLine("missing number  : {0}",missingNumber);
        }
    }

Output
missing number : 5

Method 2:

Algorithm:
step1: XOR all the array elements, let the result of XOR be X1.
step2: XOR all numbers from 1 to n, let XOR be X2.
step3: XOR of X1 and X2 gives the missing number.

C# Programming Example

using System;
 class Find_Missing_Number
    {
        static void Main(string[] args)
        {
            //array to find the missing number between 1 and 10
            // Simplicity, We will take number 1 to 10 i where Number 5 is missing in the sequence.
            int[] arr = { 1, 2, 3, 4, 6, 7, 8, 9, 10 };

            int missingNumber;
            int x1or = 0;
            int x2or = 0;
            // Accoreding to series rule, calculating sum of total numbers upto 10
            //sum of first n natutal numbers=n*(n+1)/2
           

            // Missing number is calculating.
            //Perform xor on all the elements of the array
            foreach (int item in arr)
            {
                x1or = x1or ^ item;
            }
            //perforn xor on 1 to n+1
            for (int i = 1; i <= arr.Length+1; i++)
            {
                x2or = x2or ^ i;

            }

            missingNumber=(x1or^x2or);

            Console.WriteLine("missing number  : {0}", missingNumber);
        }
        
    }

Output
missing number : 5