0

I have this void function that I call at a certain point on my main()

void calc(int dim){

 int a[dim],i,j,temp;

 for(int i=0;i<dim;i++)
  {
   printf("\n\n Type a number - [%d/%d]: \t",i+1,dim);
   scanf("%d", &a[i]);       
  }

 for(i=0;i<dim;i++)
  {

   for(j=i+1;j<dim;j++) {

    if(a[i]==a[j])
    {
     continue;    
    }

    else
      {
       temp=a[i];
       a[i]=a[j];
       a[j]=temp;
       printf("%d", a[j]);
      }
    }
  }

  for(i=0;i<dim;i++)
   printf("%d", a[i]);
}

The input paramenter dim is the dimension of the array. The code you see works perfectly because it sorts the numbers inside my array.

If the user types 4 5 8 7 5 as input numbers, I want to have an output like this: 8 7 5 4. I must remove the repeated number, so I worte:

if(a[i]==a[j])
    {
     continue;    
    }

By the way the output is still 8 7 5 5 4. How could I fix this?

4
  • possible duplicate of Algorithm: efficient way to remove duplicate integers from an array Commented Jul 25, 2013 at 16:36
  • By the way, you could look at std::vector in the C++ stl - this may help you in future if you didn't already know about it Commented Jul 25, 2013 at 16:41
  • Its question is tagged with C language even if it looks like c++ because of it i declaration in a loop Commented Jul 25, 2013 at 16:43
  • The declaration of i in a loop looks like C supported by the old standard (C99), let alone the current standard (C2011, C11). Only certain widely used C compilers are still stuck in the C89 time-warp (yes, that's MSVC). Commented Jul 25, 2013 at 16:56

2 Answers 2

3

When you spot the duplicate, you need to 'remove' it. You should probably move the last item in the list to the current spot (a[j]) and then decrement dim.

You'll need to consider how the possibly modified dimension is returned to the calling code, but then you also have an issue with how does other code get at the array that's local to the function.

Sign up to request clarification or add additional context in comments.

Comments

-1

You are moving the number before it is checked. That's why you are missing it. I suggest sorting them first and then check for duplicates later (current == prev). Maybe other techniques would work too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.