Detecting duplicate elements in an array involves checking whether there are any elements that appear more than once within the array.
Example:
#include <stdio.h>
#define MAX_SIZE 100
// Function to check for duplicate elements in an array
void findDuplicates(int array[], int size) {
// Iterate through the array
for (int i = 0; i < size – 1; i++) {
for (int j = i + 1; j < size; j++) {
// If duplicate found
if (array[i] == array[j]) {
printf(“Duplicate element found: %d\n”, array[i]);
}
}
}
}
int main() {
int arr[MAX_SIZE] = {2, 4, 6, 2, 7, 4, 8, 1, 9, 5}; // Example array
int size = 10; // Current size of the array
// Call the findDuplicates function to check for duplicates
findDuplicates(arr, size);
return 0;
}
Explanation:
- We have a function
findDuplicatesthat takes the array and its size as parameters. - Inside
findDuplicates, we use nested loops to iterate through the array. - For each element at index
i, we compare it with every element at indices greater thani(starting fromi + 1). - If we find any two elements that are equal, we print a message indicating the presence of a duplicate element.
- In the
mainfunction, we define an example arrayarrand its sizesize. - We call the
findDuplicatesfunction to check for duplicate elements in the arrayarr. - If duplicates are found, their values are printed. Otherwise, no output is produced, indicating no duplicates were found.