C program to remove duplicates from an integer array while preserving insertion order using a simple O(n^2) algorithm for clarity and ease of use.
#include <stdio.h>
// Function that removes duplicates from an array while maintaining the original order
// input: original array, its size
// output: array without duplicates, pointer to the size of the resulting array
void removeDuplicates(int input[], int inputSize, int output[], int *outputSize) {
int i, j;
*outputSize = 0; // initialize the size of the output array
for (i = 0; i < inputSize; i++) {
int trovato = 0; // flag to indicate if the element is already present
// check if input[i] is already present in output
for (j = 0; j < *outputSize; j++) {
if (input[i] == output[j]) {
trovato = 1; // duplicate found
break;
}
}
// if not found, add the element to the output array
if (!trovato) {
output[*outputSize] = input[i];
(*outputSize)++;
}
}
}
int main() {
// Sample array with duplicates
int arrayOriginale[] = {4, 5, 9, 4, 5, 7, 9, 1};
int dimensioneOriginale = sizeof(arrayOriginale) / sizeof(arrayOriginale[0]);
// Array to hold values without duplicates
int arraySenzaDuplicati[dimensioneOriginale];
int dimensioneSenzaDuplicati = 0;
// Remove duplicates
removeDuplicates(arrayOriginale, dimensioneOriginale, arraySenzaDuplicati, &dimensioneSenzaDuplicati);
// Print the result
printf("Original array: ");
for (int i = 0; i < dimensioneOriginale; i++) {
printf("%d ", arrayOriginale[i]);
}
printf("\n");
printf("Array without duplicates: ");
for (int i = 0; i < dimensioneSenzaDuplicati; i++) {
printf("%d ", arraySenzaDuplicati[i]);
}
printf("\n");
return 0;
}Input integer array: contains the original values with possible duplicates.
Output integer array: contains the values without duplicates, maintaining order.
removeDuplicates function: implements the logic to remove duplicates.
main function: initializes the array, calls the duplicate removal function, and prints the result.
Development environment: standard C compiler (gcc, clang, etc.).
No external libraries required, uses only stdio.h for input/output.
Configuration: no particular hardware or software configuration needed.