Tips to find the missing number in a sorted array:
Find the sum of n number using formula n=n*(n+1)/2
Find the sum of elements present in given array.
Substract (sum of n numbers – sum of elements present in the array).
Algorithm:
STEP 1: Start
STEP 2:Declare the array size.
STEP 3:Ask the user to initialize the array size.
STEP 4:Declare the array.
STEP 5:Ask the user to initialize the array elements.
STEP 6:Calculate the sum of first n natural numbers using a formula as sumtotal= n*(n+1)/2
STEP 7: Declare a variable sum to store the sum of array elements.
STEP 8: Using a for loop traverse through each element of the array.
STEP 9: Deduct each element from the total sum calculated.
STEP 10: The remaining element in the sum will be the missing element.
STEP 11: Print the sum.
STEP 12:Stop.
Code:
import java.util.Scanner;
public class MissingNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the n value: ");
int n = sc.nextInt();
int inpuArray[] = new int[n];
System.out.println("Enter (n-1) numbers: ");
for(int i=0; i<=n-2; i++) {
inpuArray[i] = sc.nextInt();
}
//Finding the missing number
int sumOfAll = (n*(n+1))/2;
int sumOfArray = 0;
for(int i=0; i<=n-2; i++)
{
sumOfArray = sumOfArray+inpuArray[i];
}
int missingNumber = sumOfAll-sumOfArray;
System.out.println("Missing number is: "+missingNumber);
}
}
Output:
The Tech Platform
Commentaires