Program to Display the distinct elements of an array in Java

Distinct Elements of an Array in Java

Distinct elements of are nothing but a unique (non-duplicate) elements present in the given array. In this article, we will discuss how to find the distinct elements of an array in java.

  • Sample Input  : 1, 3, 7 11, 3, 8, 11
  • Sample Output : 1, 3, 7, 11, 8 
Distinct elements of an array in java

Steps to find distinct elements of an array

  • Take the size of array as input n.
  • Take n space separated elements of an array as input.
  • Traverse the array from the beginning.
  • Check if the current element is found in the array again. 
  • If it is found, then do not print that element.
  • Else, print that element and continue.

Code in java

import java.util.*;
class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter size of an array");
int n=sc.nextInt(); //size of an array
System.out.println("Enter elements of an array");
int arr[]=new int[n];

for(int i=0;i<n;i++)
arr[i]=sc.nextInt();

System.out.println("Distinct elements of an array :");
boolean flag=false;
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<i;j++)
if(arr[i]==arr[j])
break;
if(i==j)
System.out.print(arr[i]+" ");
}
}
}

Output :

Enter size of an array
7
Enter elements of an array
1 3 7 11 3 8 11
Distinct elements of an array :
1 3 7 11 8