top of page
Click here to go to the home page of AskTheCode.

Write a C++ Program to count distinct value in an array| AskTheCode

Team ATC

Asked by: Umar Khan | Category: C++ ( c plus plus ) | Program to count distinct elements in an array in C++

 

#include <iostream>

using namespace std;

int distinctValueCounter(int a[], int size){

int i, j, count = 1;

for (i = 1; i < size; i++){

for (j = 0; j < i; j++){

if (a[i] == a[j]){

break;

}

}

if (i == j){

count++;

}

}

return count;

}


int main(){

int n;

cout<< "Enter the number of elements: ";

cin>>n;

int arr[n];

for(int i=0; i<n; i++){

cout<< "Enter "<<i+1 <<"th element: ";

cin>>arr[i];

}

cout << "\nThe array is:";

for(int i=0; i<n; i++){

cout << " "<<arr[i];

}

cout << "\nThe number of distinct elements is: "<<distinctValueCounter(arr, n);

return 0;

}

 
 
 

Recent Posts

See All

Comments


bottom of page