Q19. Write a code to print all distinct elements of a given integer array
Distinct Element :- Distinct elements are nothing but the unique (non-duplicate) elements present in the given array.
Algorithm Distinct Elements In An Array
//Algorithm To Print All Distinct Elements Of A Given Integer Array.
START
Step 1 -> Take array as input arr.
Step 2 -> calculate size of array
Step 3 -> for loop i to n:
for loop j to i:
if arr[i] == arr[j]:
break;
if i == j:
print arr[i]
STOP
Code for Distinct Elements In An Array
//C Program Print All Distinct Elements Of A Given Integer Array.
#include <stdio.h>
int main()
{
int arr[] = {5,4,2,5,8,8,7,5,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<n; i++)
{
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
printf(“%d “,arr[i]);
}
return 0;
}
//C++ Program Print All Distinct Elements Of A Given Integer Array.
#include <iostream>
using namespace std;
int main()
{
int arr[] = {5,4,2,5,8,8,7,5,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<n; i++)
{
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
cout << arr[i] << ” “;
}
return 0;
}
//Java Program Print All Distinct Elements Of A Given Integer Array.
public class LFC
{
public static void main(String[] args) {
int arr[] = {5,4,2,5,8,8,7,5,6,7};
int n = arr.length;
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + ” “);
}
}
}
//Python Program Print All Distinct Elements Of A Given Integer Array.
arr = [5,4,2,5,8,8,7,5,6,7]
n = len(arr)
for i in range(0, n):
d = 0
for j in range(0, i):
if (arr[i] == arr[j]):
d = 1
break
if (d == 0):
print(arr[i])
//PHP Program Print All Distinct Elements Of A Given Integer Array.
<?php
$arr = array(6, 8, 12, 8, 6, 10, 14, 2, 14);
$n = sizeof($arr);
for($i = 0; $i < $n; $i++)
{
$j;
for($j = 0; $j < $i; $j++)
if ($arr[$i] == $arr[$j])
break;
if ($i == $j)
echo $arr[$i] , ” “;
}
?>
Output
5,4,2,8,7,6
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number