C++ Program to Counting distinct elements in an array

Program to count the distinct elements

Program to count the distinct elements , In this Program we will find out the elements which are unique in the array. 

Given an integer array, we have to print all the distinct element of the input array. input array may contain duplicate elements, we have to print one element only once.

Example:

Enter the number of elements
5
Enter the array elements : 12
1
12
1
3
The number of distinct elements are 3
Program to Counting distinct elements in an array in cpp
Cpp Program to Counting distinct elements in an array

Algorithm :

Step 1. Initialize arrays.

Step 3. take array size from the user.

Step 4. Take an element of the array from the user.

Step 5.  Print the total distinct number of the array by calling  countDistinct function.

countDistinct(int a[], int n)

Step 1. Initialize count variable with one.

Step 2.  Initialize two for-loops for checking the similar elements.

Step 3.  check the condition if i and j are equal then increase a temporary variable by one.

Step 4. Return the main temporary variable that is count (print the value of count).

C++ code based on above approach :

#include <iostream>

using namespace std;
int countDistinct(int a[], int n) //Function Definition
{
int i, j, count = 1;
//Traverse the array
for (i = 1; i < n; i++) //hold an array element
{
for (j = 0; j < i; j++)
{
if (a[i] == a[j]) //Check for duplicate elements
{
break; //If duplicate elements found then break
}
}
if (i == j)
{
count++; //increment the number of distinct elements
}
}
return count; //Return the number of distinct elements
}
int main()
{
int n; //Declare array size
cout<<"Enter the number of elements \n";
cin>>n; //Initialize the array size

int arr[n]; //Array Declaration
cout<<"Enter the array elements : ";
for (int i=0;i<n;i++)
cin>>arr[i]; //Initialize the array elements

int c= countDistinct(arr,n); //Function Call
cout<<"The number of distinct elements are "<< c; //Print the number of distinct elements
return 0;
}
//Test case 1
Enter the number of elements
6
Enter the array elements : 1
2
1
2
3
3
The number of distinct elements are 3

//Test case 2
Enter the number of elements
6
Enter the array elements : 12
22
34
55
66
23
The number of distinct elements are 6

//Test case 3
Enter the number of elements
6
Enter the array elements : 2
3
4
44
6
6
The number of distinct elements are 5