Reputation: 582
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!
Upvotes: 0
Views: 1072
Reputation: 1890
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;
}
Upvotes: 2