Write a program to Print Unique Elements in Array


This is a Java program that takes an integer array input from the user and prints out the unique elements of the array. Here is a brief explanation of the code:

  • The program first imports the Scanner class from the java.util package to read input from the user.
  • The program defines a static method called getUnique that takes an integer array a and its length n as input.
  • The getUnique method uses nested loops to compare each element of the array with all previous elements to check if it is unique. If an element is found to be a duplicate, the inner loop breaks and moves to the next element.
  • If the element is not found to be a duplicate, it is printed to the console.
  • The main method first reads the length of the array from the user and creates an array of that size.
  • It then prompts the user to enter the elements of the array and stores them in the array using a for loop.
  • Finally, the main method calls the getUnique method to print out the unique elements of the array.

Source Code

import java.util.Scanner;
public class Array_Unique_Element
{
	static void getUnique(int a[], int n)
	{
		for (int i = 0; i < n; i++)
		{
			int j;
			for (j = 0; j < i; j++)
			if (a[i] == a[j])
				break;
			if (i == j)
			System.out.print( a[i] + " ");
		}
	}	
	public static void main (String[] args)
	{
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
        for(int i=0;i<l;i++)
        {
            System.out.printf("Element of a[%d] :",i);
            a[i]=input.nextInt();
        }
		System.out.println("\nDisplay Array Unique Elements...\n");
		getUnique(a, l);
 
	}
}

Output

Enter the Array Limit :5
Element of a[0] :10
Element of a[1] :20
Element of a[2] :40
Element of a[3] :10
Element of a[4] :20

Display Array Unique Elements...

10 20 40

Example Programs