Write C program to delete all duplicate elements from an array



techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#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 num; // Total number of elements in array
    int i, j, k;

    //Enter size of array
    printf("Enter size of the array : ");
    scanf("%d", &num);

    //Reading elements of array
    printf("Enter elements in array : ");
    for(i=0; i<num; i++)
    {
        scanf("%d", &arr[i]);
    }

    // Finding all duplicate elements in array

    for(i=0; i<num; i++)
    {
        for(j=i+1; j<num; j++)
        {
            //If any duplicate found */
            if(arr[i] == arr[j])
            {
                // Delete the current duplicate element
                for(k=j; k<num; k++)
                {
                    arr[k] = arr[k + 1];
                }

                //Decrement size after removing duplicate element
                num--;

                // 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<num; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
}

Result

C language

     





Related Topics




Popular Posts