jakim_M
jakim_M

Reputation: 21

finding duplications in arrays

i am very fresh with C. Currently I am writing a program which should display duplicates in array. Program reads (from user), N numbers (but N < 100), and after that display numbers which are duplicated. My code work, but i have problem with display. For example, when it is 5 elenets array numb[5] = {1, 2, 2, 2, 3}, program display 2 three times, and it should display 2 one time.

#include <stdio.h> 
    int main () 
    {
        int n, i, j, numbers[100]={0};
        printf("number of elements (max 100):");
        scanf("%i", &n);
        printf("enter elements:");

        for (i = 0; i < n; i++)
        {
           scanf("%i", &numbers[i]);
        }
        for (i = 0; i < n; i++)
        {
           for j = i+1; j < n; j++)
           {
               if (numbers[i] ==numbers[j])
               {
                  printf("duplicates:%i\n", numbers[i]);
               }
           }
        }
     }

Upvotes: 0

Views: 84

Answers (1)

Achal
Achal

Reputation: 11921

Once numbers[i] ==numbers[j] true you need to either delete duplicates(shifting) or some other ways to not to print duplicates again. So write logic for that.

here is my edit in your code :

#include <stdio.h>
int main ()
{
        int n, i, j,k, numbers[100]={0};
        printf("number of elements (max 100):");
        scanf("%i", &n);
        printf("enter elements:");

        for (i = 0; i < n; i++)
        {
                scanf("%i", &numbers[i]);
        }
        for (i = 0; i < n; i++)
        {
                for (j = i+1; j < n; j++)
                {
                        if (numbers[j] ==numbers[j+1])//once true shift all elements by once 
                        {
                                for(k=j; k<n; k++)//loop for shifting elemenst
                                        numbers[k]=numbers[k+1];
                                j--;//again starts comparing from previous position
                                n--;// no of elements reduced 
                        }
                }
        }
        for(i=0; i<n ;i++)
                printf("%d \n",numbers[i]);
   return 0;
}

I hope it helps.

Upvotes: 1

Related Questions