Find all missing numbers from a sorted array in Java

Hi coders! today we are going to see how to find all the missing numbers in a sorted array in Java. We all know an array is a collection of similar data type data. if we want to store data of similar data type we store it under a single name called array. Suppose we want to find all the missing numbers from a sorted array. Here sorted array means all the elements in ascending order.

How to find all missing numbers from a sorted array

let’s see how to do it.

  1. We will enter the size of the array. Then we will insert the elements one by one.
  2. We will assign the first element to a variable.
  3. This variable value will be compared to the array elements.
  4. If found, the index of the array is incremented.
  5. Otherwise, the variable is printed.
  6. Then the variable is incremented.

Here the code for the same.

Java program: Find missing numbers from a sorted array

package projrcty;

import java.util.Scanner; /*find the missing number in array*/

public class find_missing {

  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
         System.out.println("enter size of array");
         int size=sc.nextInt();
         System.out.println("enter array");
         int arr[]=new int[size];
         for(int i=0;i<size-1;i++)
         {
             arr[i]=sc.nextInt();
         }
         int j=0,k=arr[0];
       
         while(j<size-1)
         {   
             if(arr[j]==k)
            	{j++;}
             else
            { System.out.println(k);
            }
            k++;
         }	
    
    

  }

}

Output:

enter size of array
5
enter array
2
5
6
8
14
3 4 7 9 10 11 12 13

I hope you understand the code.

Leave a Reply

Your email address will not be published.