Java program to find non-repeating elements in an array

Non Repeating elements in an Array

In this section, we will learn the Java Program to Find the Non Repeating elements in an Array or the elements that do not repeat itself.

Given an array, print all element whose frequency is one.

Example

Input: a[]= { 1,2,5,2,6,7,5 }

Output: 1,6,7

There is three number which has one frequency.

so there is three number which is not repeated.

Non Repeating elements in an Array in java
Non Repeating elements in an Array in Java

Algorithm

Step 1. Initialize arrays.

Step 2. Declare the scanner class for taking input.

Step 3. take array size from the user.

Step 4. Take an element of the array from the user.

Step 5.  Call the NonRepeating method which gives us non-repeating element from the array.

NonRepeating(int a[], int size)

Step 1. Initialise temp variable.

Step 2.  Initialise the outer for loop for process each element of the array.

Step 3.  Initialise the inner loop for checking that the current number match with other number or not. if the current element match with another element that increases a temporary variable by one.

Step 4. If count is zero so print the current element.

Java code

import java.util.Scanner;
public class Main
{
      public static void NonRepeating(int a[],int n)
      {
          int count;
          System.out.println("Non Repeating element in array");

         for(int i=0;i<n;i++)
         {
             count=0;
             //initialise the for loop for checking the elenemnt which are not repeated)
             for (int j = 0; j < n; j++)
             {
                  //check the condition if any number is same so
                //incre
                if(a[i]==a[j] && i!=j)
                       count++;
             }
            //if count became zero so print the current element
          if(count==0)
              System.out.print(a[i]+" ");
         }
       }

       public static void main(String[] args) 
       {
          Scanner sc=new Scanner(System.in);
          int[] a=new int[50];
          System.out.println("enter size of an array");
          int size=sc.nextInt();
          System.out.println("enter elements of an array");
          for(int i=0;i<size;i++)
          {
               a[i]=sc.nextInt();
          }
          //call the NonRepeating function
          NonRepeating(a,size);
       }
}

output

Enter size of an array
6
Enter elements of array
12
2
12
3
9
2
non-repeating elements are
3,9