Duplicate Elements: Find duplicates in an array
This program demonstrates how to find duplicate elements in an array using C. The algorithm iterates through the array and uses another array to track seen elements. If an element is found again, it is identified as a duplicate.
C Program
#include <stdio.h>
#include <stdbool.h>
void findDuplicates(int arr[], int size) {
bool seen[1000] = {false}; // Assuming values are less than 1000
bool duplicates[1000] = {false};
for (int i = 0; i < size; i++) {
if (seen[arr[i]]) {
duplicates[arr[i]] = true;
} else {
seen[arr[i]] = true;
}
}
printf("Duplicate elements: ");
bool found = false;
for (int i = 0; i < 1000; i++) {
if (duplicates[i]) {
printf("%d ", i);
found = true;
}
}
if (!found) {
printf("No duplicates found.");
}
printf("\n");
}
int main() {
int array[] = {1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10};
int size = sizeof(array) / sizeof(array[0]);
findDuplicates(array, size);
return 0;
}
Explanation
The program includes the following components:
#include <stdio.h>: Includes the standard I/O library for input and output functions.#include <stdbool.h>: Includes the standard Boolean library for usingtrueandfalsevalues.void findDuplicates(int arr[], int size): Defines a function that takes an array of integers and its size as input and prints the duplicate elements.bool seen[1000] = {false};: Initializes a Boolean array to keep track of elements that have been encountered in the array. The size 1000 is assumed based on the possible range of values in the array.bool duplicates[1000] = {false};: Initializes a Boolean array to store duplicate elements.for (int i = 0; i < size; i++): Iterates through each element in the array.if (seen[arr[i]]): Checks if the element is already in theseenarray. If it is, the element is a duplicate.duplicates[arr[i]] = true;: Adds the duplicate element to theduplicatesarray.seen[arr[i]] = true;: Marks the element as seen.printf("Duplicate elements: ");: Prints the start of the duplicate elements output.for (int i = 0; i < 1000; i++): Iterates through theduplicatesarray to print the duplicate elements.if (!found): Checks if no duplicates were found and prints an appropriate message.int main(): The main function that initializes an array and calls thefindDuplicatesfunction.printf("%d ", i): Prints each duplicate element.
The example array int array[] = {1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10}; contains the duplicates 2, 3, and 10. When the findDuplicates function is called, it will print:
Duplicate elements: 2 3 10
Explanation
- C Program: The provided C program uses arrays to identify duplicate elements in an array. The
findDuplicatesfunction iterates through the input array, using a Boolean arrayseento track elements that have been encountered. If an element is already in theseenarray, it is added to theduplicatesarray. - Output: The output of the program will list all the duplicate elements found in the array.
