0

If I have an array of N elements in C programming, how can I exchange a particular pair of elements?

For instance given the array:

double variable[N] = {1, 2, ..., i-1, i, i+1, ..., N-1, N }

How could I exchange element i for i+1 in such a way that the new system is given by:

double variable[N] = {1, 2, ...,i-1, i+1, i, ..., N-1, N } 

My attempt is to make a temporary variable:

{ double temp = element i ;     element i =element i+1 ;   element i+1 = temp;   }

I am dubious as to whether this will advance the variable by one or swap them as required? Unfortunately I am not sure how to implement this in code or even if this is the correct way to do it? In addition, I am unsure of how to cater for when i=N, so that elements cycle back down through the array.

I am very new to programming and very much appreciate any help offered. Thank you!

2
  • Look up indexing an array and assigning elements to an index in an array Commented Oct 10, 2015 at 23:23
  • I would suggest creating a swap routine that takes two pointers and then simply using it like this: swap(&element[i],&element[i+1]); Commented Oct 10, 2015 at 23:38

1 Answer 1

2

if you know which elements to exchange, you could do :

if (i+1 < N)
{
  double temp = variable[i];
  variable[i] = variable[i+1];
  variable[i+1] = temp;
}

I check first if i+1 is inferior to N (remember the index of an array begins by 0) to prevent reading outside the array. Then I do the exchange.

If I understood you, if you have to exchange the last element, you would like that it be done with the first element. In that case, you could change the former if to :

if (i+1 <= N)
{
  double temp = variable[i];
  variable[i] = variable[(i+1)%N];
  variable[(i+1)%N] = temp;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Or just int toswap = i + 1 < n ? i + 1 : 0; (or (i + 1) % n)
Mod happens before addition btw.
Yes you are right, and yes right again , my mistake. Thanks !
@Blake_Lead Thank you very much for your time Blake, I really appreciate it! Out of interest how could I make the exchanges swap back down through the loop once they reach N, for instance i=N swaps with j=N-1, to cycle back and forth through the array?
You are very welcome. To perform what you ask, I think I would use a flag variable that would change value when N is first reached. I would then test the value of this flag variable : if it changed, I would change the order of operation.

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.