A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

Remove duplicate elements from array C Program

Arrays: An array is the collection of similar type of data items stored at contiguous memory locations. Arrays may or may not contain duplicate elements. Using for loop we can easily remove duplicate items.

Arrays are the derived data type in C which can store the fundamental type of data such as int, float, double, char. Arrays can be 1-D, 2-D or Multidimensional.

Description:

i, j and k – Loop control variables.
size – Number of elements in the array.
a – 1 D array.
for loops are used to read, print and remove duplicate items from array.
Input : Array with duplicate items.
Output : Array with out duplicate items.

Algorithm to remove duplicate elements from an array:

STEP 1: START
STEP 2: READ the size(number of elements) of array
              READ size
STEP 3: READ the elements of array
              LOOP from i = 0 to size
                             READ a(i)
STEP 4: REPEAT STEP 5
              LOOP from i = 0 to size
STEP 5: REPEAT STEP 6
              LOOP from j = (i + 1) to size
STEP 6: COMPARE current and next item in the array
              if a(i) = a(j)
              REMOVE duplicate and arrange array
              LOOP from k = j to (size – 1)
              a(k) = a(k + 1)
              REDUCE the array size
              Size = size – 1
STEP 7: PRINT the array
              LOOP from i = 0 to size
                             PRINT a  
STEP 8: END

Example: C Program to remove duplicate items from unsorted array.

#include<stdio.h>
#include<conio.h>
int main()
{
    int a[100]; 
    int size;          
    int i, j, k;       
    printf("Enter size of the array : ");
    scanf("%d", &size);
    printf("Enter elements of array : ");
    for(i=0; i<size; i++)
        scanf("%d", &a[i]);
    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
            if(a[i] == a[j])
            {
                for(k=j; k < size - 1; k++)
                {
                    a[k] = a[k + 1];
                }
                size--;
                j--;
            }
        }
    }
    printf("Array elements after deleting duplicates : ");
    for(i=0; i<size; i++)
        printf("%d\t", a[i]);
    getch();
    return 0;
}

Output 1:

Enter size of the array : 5
Enter elements of array : -2 2 4 -2 4
Array elements after deleting duplicates : -2 2 4

Output 2:

Enter size of the array : 8
Enter elements of array : 4 2 4 -11 11 1 -11 9
Array elements after deleting duplicates : 4 2 -11 11 1 9

QUIZ:

1] Array is the collection of ____________ type of data.

  1. homogenous
  2. heterogenous
  3. mixed
  4. can not say

2] Arrays can contain duplicate items.

  • TRUE
  • FALSE