w3resource

C Exercises: Print all unique elements of an array

C Array: Exercise-6 with Solution

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

Pictorial Presentation:

C Exercises: Print all unique elements of an array

Sample Solution:

C Code:

#include <stdio.h>
int main()
{
    int arr1[100], n,ctr=0;
    int i, j, k;
       printf("\n\nPrint all unique elements of an array:\n");
       printf("------------------------------------------\n");	
       printf("Input the number of elements to be stored in the array: ");
       scanf("%d",&n);
       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
	      printf("element - %d : ",i);
	      scanf("%d",&arr1[i]);
	    }
    printf("\nThe unique elements found in the array are: \n");
    for(i=0; i<n; i++)
    {
        ctr=0;
        for(j=0,k=n; j<k+1; j++)
        {
            /*Increment the counter when the seaarch value is duplicate.*/
            if (i!=j)
            {
		       if(arr1[i]==arr1[j])
              {
                 ctr++;
               }
             }
        }
       if(ctr==0)
        {
          printf("%d ",arr1[i]);
        }
    }
       printf("\n\n");
}

Sample Output:

Print all unique elements of an array:
------------------------------------------
Input the number of elements to be stored in the array: 4
Input 4 elements in the array :
element - 0 : 3
element - 1 : 2
element - 2 : 2
element - 3 : 5

The unique elements found in the array are:
3 5

Flowchart:

Flowchart: Print all unique elements of an array.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to count a total number of duplicate elements in an array.
Next: Write a program in C to merge two arrays of same size sorted in decending order.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - What is the argument for printf that formats a long?

Put an l (lowercased letter L) directly before the specifier.

unsigned long n;
long m;

printf("%lu %ld", n, m);

Ref : https://bit.ly/3dIwfkP