Q. Write an algorithm and program 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.
Distinct Elements In An Array - Algorithm
//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
Distinct Elements In An Array Program
//C Program Print All Distinct Elements Of A Given Integer Array. #include <stdio.h> int main() { int arr[] = {6, 8, 12, 8, 6, 10, 14, 2, 14}; 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[] = {6, 8, 12, 8, 6, 10, 14, 2, 14}; 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[] = {6, 8, 12, 8, 6, 10, 14, 2, 14}; 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 = [6, 8, 12, 8, 6, 10, 14, 2, 14] 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])
//C# Program Print All Distinct Elements Of A Given Integer Array. using System; class LFC { static void Main() { int []arr = {6, 8, 12, 8, 6, 10, 14, 2, 14}; 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) Console.Write(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] , " "; } ?>
//C Program Print All Distinct Elements Of A Given Integer Array. #include <stdio.h> int main() { int arr[] = {6, 8, 12, 8, 6, 10, 14, 2, 14}; 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; }
Output
6, 8, 12, 10, 14, 2
Recommended Programs
Write an algorithm and program of binary search.Write an algorithm and program to reverse a string.