Printing only unique elements in an array

423 Views Asked by At

Edit: I need to maintain the order in which the elements are present in the original array, so sorting won't work.

I have a 1-D array containing some elements and I am using printf() in C but I only want to print an element if and only if it has not already been printed before.

I am thinking of using nested loops to compare if the element I am about to print from the current position in the array was already present in a lower index of the array but it's not working. What am I missing? Or is my whole approach wrong?

So far, I have tried this, which is not working:

int arr[20];

After this I take user input for no. of elements in p and of course, p<20. Then, user enters the elements one by one. I use scanf() for this.

for(i=1;i<=p;i++)
{
    for(j=i+1;j<=p;j++)
    {
        if(arr[i]!=arr[j])
        {
            printf("%d",arr[j]);
        }
    }
}
2

There are 2 best solutions below

0
enhzflep On

You need to check all previous items before you know if the item has already occurred.

#include <stdio.h>
#include <stdlib.h>

int compareFunc(const void *op1, const void *op2 )
{
    int *a, *b;
    a = (int*)op1;
    b = (int*)op2;
    return *a - *b;
}

void printUnique(int *array, int numElems)
{
    int curPrintIndex, curCompareIndex;
    char alreadySeen;

    for (curPrintIndex=0; curPrintIndex<numElems; curPrintIndex++)
    {
        alreadySeen = 0;
        for (curCompareIndex=0; curCompareIndex<curPrintIndex; curCompareIndex++)
        {
            if (array[curCompareIndex] == array[curPrintIndex])
            {
                alreadySeen = 1;
                break;
            }
        }
        if (alreadySeen == 0)
            printf("%d\n", array[curPrintIndex]);
    }
}

int main()
{
    const int numItems = 100;
    int *array, i, lastVal;

    array = calloc(numItems, sizeof(int) );

    for (i=0; i<numItems; i++)
        array[i] = rand()%numItems;

    printUnique(array, numItems);

    free(array);
    return 0;
/*
    qsort(array, numItems, sizeof(int), compareFunc);

    printf("%d\n", array[0]);
    lastVal = array[0];

    for (i=1; i<numItems; i++)
    {
        if (array[i] != lastVal)
        {
            lastVal = array[i];
            printf("%d\n", array[i]);
        }
    }
*/
}
0
BLUEPIXY On
#include <stdio.h>

int main(void){
    int arr[20] = { 4,8,4,2,4,8,1,3,2,7 };//the elements are positive integers.
    int i, j, p = 10;

    for(i=0;i<p-1;i++){
        if(arr[i] < 0)
            continue;
        for(j=i+1;j<p;j++){
            if(arr[j] > 0 && arr[i]==arr[j])
                arr[j] *= -1;
        }
    }
    for(i=0; i < p; ++i)
        if(arr[i] > 0)
            printf("%d ", arr[i]);
    puts("");
    return 0;
}