数组的所有不同元素都将被打印,即数组中的所有元素仅被打印一次,而重复的元素不会被打印。一个例子如下。Array = 1 5 9 1 4 9 6 5 9 7
Distinct elements of above array = 1 5 9 4 6 7
演示该程序的程序如下。
示例public class Example {
public static void main (String[] args) {
int arr[] = {1, 5, 9, 1, 4, 9, 6, 5, 9, 7};
int n = arr.length;
int i, j;
System.out.print("The array is: ");
for (i = 0; i
System.out.print(arr[i] + " ");
System.out.print("\nThe distinct elements of above array are: ");
for (i = 0; i
for (j = 0; j
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
}
}
}
输出结果The array is: 1 5 9 1 4 9 6 5 9 7
The distinct elements of above array are: 1 5 9 4 6 7
现在让我们了解上面的程序。
首先显示原始数组。该数组可能包含重复的元素。证明这一点的代码片段如下所示-System.out.print("The array is: ");
for (i = 0; i
System.out.print(arr[i] + " ");
现在,使用嵌套的for循环来确保仅显示数组的不同元素。外循环从0到n运行,内循环确保仅在之前未发生过的情况下才打印元素。证明这一点的代码片段如下所示-System.out.print("\nThe distinct elements of above array are: ");
for (i = 0; i
for (j = 0; j
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
}