Find missing number.

Find missing number from given range of 1 to n.

Solution:

Algorithm:
  1. Calculate the sum of first n natural numbers as total= n*(n+1)/2
  2. create a variable sum to store the sum of array elements.
  3. Traverse the array from start to end.
  4. Update the value of sum as sum = sum + array[i]
  5. print the missing number as total – sum

// Java program to find missing Number

class Main {
// Function to find missing number
static int findMissingNo(int a[], int n)
{
int i, total;
total = (n + 1) * (n + 2) / 2;//calculates total for original range
for (i = 0; i < n; i++)
total -= a[i];//this will yield the missing number by continuously subtracting elements
return total; // from total
}

/* program to test above function */
public static void main(String args[])
{
int a[] = { 1, 2, 4, 5, 6, 7, 8 };
int miss = findMissingNo(a, 7 );
System.out.println(miss);
}
}

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.