Array Exercises
Write a C program to delete duplicate elements from array. How to remove duplicate elements from array in C programming. After performing delete operation the array should only contain unique integer value. Logic to delete duplicate elements from array.
Required knowledge
Basic C programming, If else, c-Arrays, C Loops
Logic to delete duplicate elements from array
Step by step descriptive logic to delete duplicate elements from array.
- Input size and elements in array from user. Store it in some variable say size and arr.
- To find duplicate elements in given array we need two loops. Run an outer loop from 0 to size. Loop structure must look like for(i=0; i<size; i++). This loop is used to select each element of array and check next subsequent elements for duplicates using another nested loop.
- Run another inner loop to find first duplicate of current element. Run an inner loop from i + 1 to size. The loop structure should look like for(j=i+1; j<size; j++).
- Inside the inner loop check for duplicate element. If a duplicate element is found then delete that array element. Also if a duplicate element is found then decrement size of array i.e. size = size - 1.
Program to delete duplicate elements from array
/** * C program to delete all duplicate elements from array */ #include <stdio.h> #define MAX_SIZE 100 // Maximum size of the array int main() { int arr[MAX_SIZE]; // Declares an array of size 100 int size; // Total number of elements in array int i, j, k; // Loop control variables /* Input size of the array */ printf("Enter size of the array : "); scanf("%d", &size); /* Input elements in the array */ printf("Enter elements in array : "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } /* * Find duplicate elements in array */ for(i=0; i<size; i++) { for(j=i+1; j<size; j++) { /* If any duplicate found */ if(arr[i] == arr[j]) { /* Delete the current duplicate element */ for(k=j; k<size; k++) { arr[k] = arr[k + 1]; } /* Decrement size after removing duplicate element */ size--; /* If shifting of elements occur then don't increment j */ j--; } } } /* * Print array after deleting duplicate elements */ printf("\nArray elements after deleting duplicates : "); for(i=0; i<size; i++) { printf("%d\t", arr[i]); } return 0; }