C - Program - Remove Duplicate from Array

To remove duplicates from a given array in C, you can iterate through the array and maintain a separate result array to store the unique elements. Here's an example program that removes duplicates from an array:

#include <stdio.h>
#define MAX_SIZE 100
int removeDuplicates(int arr[], int n) {
    if (n == 0 || n == 1) {
        return n;
    }
    int result[MAX_SIZE];
    int j = 0;
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            result[j++] = arr[i];
        }
    }
    result[j++] = arr[n - 1];
    for (int i = 0; i < j; i++) {
        arr[i] = result[i];
    }
    return j;
}
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
int main() {
    int arr[MAX_SIZE];
    int n;
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    printf("Enter the elements of the array: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    printf("Original array: ");
    printArray(arr, n);
    int newSize = removeDuplicates(arr, n);
    printf("Array after removing duplicates: ");
    printArray(arr, newSize);
    return 0;
}

In this program, the removeDuplicates() function takes an array arr and its size n as input. It creates a separate result array to store the unique elements. It iterates through the arr array and checks if the current element is equal to the next element. If they are not equal, it adds the current element to the result array. Finally, it copies the elements from the result array back to the arr array, overwriting the original array.

The function returns the size of the updated array without duplicates.

The printArray() function is used to print the elements of an array.

In the main() function, we input the size of the array n and its elements from the user. We then call the removeDuplicates() function, passing the array and its size. The updated array without duplicates is printed using the printArray() function.

You can run this program and enter the size and elements of the array to see the array with duplicates removed.

Note: This program assumes that the array does not exceed the maximum size specified by MAX_SIZE. You can adjust the value of MAX_SIZE as needed.