Tuesday, November 26, 2019

Write a program in C to print all unique elements in an array

#include<stdio.h>
int main()
{
    int arr[20], freq[20];
    int size, i, j, count;

    /* Input size of array and elements in array */
    printf("Enter size of array: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    for(i=0; i<size;i++)   

  {
        scanf("%d", &arr[i]);
        freq[i] = -1;
    }

    /* Find frequency of each element */
    for(i=0; i<size;i++)   

    {
        count = 1;
        for(j=i+1; j<size;j++)        

      {
            if(arr[i] == arr[j])
            {
                count++;
                freq[j] = 0;
            }
        }

        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }

    /* Print all unique elements of array */
    printf("\nUnique elements in the array are: ");
    for(i=0; i<size;i++)   

   {
        if(freq[i] == 1)
        {
            printf("%d ", arr[i]);
        }
    }

    return 0;
}

--------------------------------------------------------------------------------------------------------
OUTPUT:
Enter size of array: 6
Enter elements in array: 2
4
5
2
3
4

Unique elements in the array are: 5 3 

------------------------------------------------------------------------------------------------------
Enter size of array: 9
Enter elements in array: 1
2
3
4
5
6
1
2
3

Unique elements in the array are: 4 5 6

No comments:

Post a Comment