- Write a C program to count duplicate elements in an array.
- How to count duplicate elements in an integer array
Required Knowledge
- C printf and scanf functions
- For loop in C
- Arrays in C
Algorithm to count duplicate elements in an array
Count repeated elements in an array java: Let inputArray is an integer array having N elements.
- For every element inputArray[i], where (0<=i<=N-1). Search for it’s duplicate element from index i+1 to N-1.
- If duplicate element found, increment the counter and stop searching further for inputArray[i].
C program to find count of duplicate elements in an array
#include <stdio.h> int main() { int inputArray[100]; int i, j, elementCount, count = 0; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers\n", elementCount); /* Read array elements */ for(i = 0; i < elementCount; i++){ scanf("%d", &inputArray[i]); } /* * Take an element and compare it with all elements * after that till we find a duplicate element */ for(i = 0; i < elementCount ; i++) { for(j = i+1; j < elementCount; j++) { if(inputArray[i]==inputArray[j]) { /* One Duplicate Element Found */ count++; break; } } } printf("Duplicate Element Count : %d\n", count); return 0; }
Output
Enter Number of Elements in Array 8 Enter 8 numbers 1 2 3 4 1 2 3 4 Duplicate Element Count : 4