➤ Process Remove Duplicates Items In An Array .
When the same number of elements occurs in sorted or unsorted array, then
the elements of the array is called the duplicate elements. And we need to
delete these duplicate elements or same number from an array to make
the resultant array consists of unique elements.
For example, there is an integer type array arr[10] that contains { 5, 8, 3, 3, 5, 9} elements.
In this array, 3 and 5 occurs two times. Hence, these elements are duplicate elements.
So, after deleting the duplicate elements from an array arr[], we get 5, 8, 3,9 elements.
➤ Steps to delete the duplicate elements from unsorted array
Step 1: Input the size of an array from the user and store into the size variable.
Step 2: Use for loop to read the elements of an array and store in arr[i] variable.
Step 3: To get the duplicate elements from an array we need to use two for loops.
Where the first loop start from 0 to size. And the structure of the loop is:
for (i = 0; i < size; i++).
//Another loop selects each element of the array and compare with the
corresponding element to get the duplicate elements. And the structure of the inner loop is:
for (j = i + 1; j < size; j++) and the code to find the subsequent same element is:
if (arr[i] == arr[j]).
Step 4: If any duplicate element is encountered, delete the duplicate element from an array
and the size of array is decrement by 1 such that, size = size - 1.
Step 5: After that, print the unique elements of an array and the code is:
for (i = 0; i < size; i++)
{
printf ("%d \t" , arr[i]);
}
- ➤ Program For Remove Duplicates Items In An Array in C Language.
- #include<stdio.h>
- int main()
- {
- int arr[50];
- int i,j,k,len;
- // Enter the size of array (Number of elements in array)
- printf("Enter the size Of Array :\n");
- scanf("%d",&len);
- //Enter the all initialize number of elements in array
- printf("Enter %d elements for the array:\n",len);
- for(i=0; i<len ; i++)
- scanf("%d",&arr[i]);
- for(i=0; i< len-1 ; i++){
- for(j=i+1; j<len; j++){
- if(arr[j] == arr[i]){
- k=j;
- while(k<(len-1))
- {
- arr[k] = arr[k+1];
- k++;
- }
- len--;
- j=i;
- }
- }
- }
- // Here results print after removing all the duplicates from Array.
- printf("The array after removing duplicates Elements :\n");
- for(i=0; i < len; i++)
- printf(" %d",arr[i]);
- return 0;
- }
- ➤ OUTPUT:
- Enter the size Of Array :
- 6
- Enter 6 elements for the array:
- 34
- 45
- 56
- 34
- 78
- 89
- The array after removing duplicates Elements :
- 34 45 56 78 89