Write a program to allow the user to input integers into a one-dimensional array of size N.
Now remove duplicate elements from this array and display the unique elements.
Example:
INPUT:
N = 10
69
45
45
25
34
40
34
41
29
16
OUTPUT:
The result after removing duplicate numbers:
69 45 25 34 40 41 29 16
import java.io.*;
class Eliminate{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Array size: ");
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
int temp[] = new int[n];
System.out.println("Enter array elements:");
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(br.readLine());
temp[0] = a[0];
int len = 1;
int index = 0;
for(int i = 1; i < a.length; i++){
if(available(temp, a[i]))
continue;
else{
len++;
temp[++index] = a[i];
}
}
a = new int[len];
for(int i = 0; i < a.length; i++)
a[i] = temp[i];
System.out.println("Result:");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + "\t");
}
public static boolean available(int a[], int element){
boolean status = false;
for(int i = 0; i < a.length; i++){
if(a[i] == element){
status = true;
break;
}
}
return status;
}
}
3 replies on “Eliminate Duplicate Elements from an Array”
Sir,2 programs are given which states that:
1) WAP in JAVA to accept n numbers in a single dimensional array.Delete an element from the array and display the new list after deletion.
Sample Input:
n=10
69
45
49
25
87
40
34
41
29
16
Enter the number to be deleted:45
Sample output:
The new list after deleting an element from the array:
69
49
25
87
40
34
41
29
16
How to do this program by creating another array?
2) WAP in JAVA to accept some numbers to create m x m matrix(m=size of matrix).Now display the sum of all the numbers except the 2 diagonal numbers also display the highest number among them.(m>2&&m<10)
Here is the link to the solution of the matrix problem.
Refer to the second program in this post for deleting the element by searching for it in the given array.