Q:

Write C++ program to print all unique element in an array

0

Write C++ program to print all unique element in an array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
using namespace std;
 
int main()
{
    int arr[100], size, isUnique;
    int i, j, k;
 
    //Reads size of the array
    cout<<"Enter size of array: ";
    cin>>size;
 
    //Reads elements in array
    cout<<"Enter elements in array: ";
    for(i=0; i<size; i++)
    {
        cin>>arr[i];
    }
 
    //Removing all duplicate elements from the array
    for(i=0; i<size; i++)
    {
        // Assuming  cuurent element is unique */
        isUnique = 1;
 
        for(j=i+1; j<size; j++)
        {
 
            //If any duplicate element is found
 
            if(arr[i]==arr[j])
            {
                // Removing duplicate element
                for(k=j; k<size-1; k++)
                {
                    arr[k] = arr[k+1];
                }
 
                size--;
                j--;
                isUnique = 0;
            }
        }
 
        /*
        If array element is not unique
        then also remove the current element
         */
        if(isUnique != 1)
        {
            for(j=i; j<size-1; j++)
            {
                arr[j] = arr[j+1];
            }
 
            size--;
            i--;
        }
    }
    //Printing all unique elements in array
    cout<<"All unique elements in the array are: ";
    for(i=0; i<size; i++)
    {
       cout<<arr[i]<<"\t";
    }
    return 0;
}

Result:

Enter size of array: 10

Enter elements in array: 1

2

3

5

3

5

6

9

7

8

All unique elements in the array are: 1 2       6       9       7       8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write C++ program to sort an array in ascending or... >>
<< Write C++ program to insert an element in array...