Shortest Way to Find Missing Element in Array in JAVA - Java2021 : Online Tutorials Hub

Java2021 : Online Tutorials Hub

JAVA | Advance Java | MySQL | Data Structure | Git | HTML | CSS | JS

Latest

Post Top Ad

Saturday, July 11, 2020

Shortest Way to Find Missing Element in Array in JAVA

Write a program to find missing element in Array
How to find Missing Element
  • Create an Array int[]arr=new int[6] //array size 6 but you can change
  • Find expected length of an array
  • Find value (sum is variable) of sum by this : expected*(expected+1)/2;
  • create variable add put value in add = 0;
  • using for loop traverse the array and assign value into add variable : add=add+array[i];
  • finally print value of an array sum-add;
Program : 

public class MissingElement
{
    public static void main(String[] args) {
        int array[]={1,2,3,5,6,7,8,9,10};
        int expected=array.length+1;
        int sum=expected*(expected+1)/2;
        int add=0;
        for (int i=0;i<array.length;i++){
            add=add+array[i];
            System.out.println("Missing Element is "+(sum-add));
        }
    }
}
Output : 



Click to next or learn with your choice
Sorting and Searching Programs
Start with your Choice
-Important Programs for Freshers
Learn Pattern Programs 
Click to Learn MySQL 
for any complaint regarding my Blog please visit contact us page and write what problem you have!

No comments:

Pages