How can I swap the values of an array(in C)?
For example I have:
Array1[] = {1,4,67};
and I want to swap this numbers, in {4, 67, 1}.
1
use a temporary variable
int Array1[] = {1, 4, 67};
int tmp = Array1[0];
Array1[0] = Array1[1];
Array1[1] = Array1[2];
Array1[2] = tmp; // old Array1[0]
To start with the basics…
Suppose the following array:
int a[5] = {1, 2, 3, 4, 5};
Now we want to swap numbers between them (for this example i’ll swap 1 with 5). You can make this on spot:
int aux = a[5];
a[5] = a[1];
a[1] = aux;
To have it nicelly you can make it into a function:
void swap_int(int* a, int* b)
{
int aux = *a;
*a = *b;
*b = aux;
}
And with this function you can call swap_int(&v[1], &v[5]);
and will produce the same result.
Use the swap function as below:
#include<stdio.h>
#include<stdlib.h>
void swap(int *a, int *b);
int main() {
int a[3] = {1,4,67};
for(int i = 0; i < 3; i++)
printf("%d ", a[i]);
printf("n");
swap(a, a + 2);
swap(a, a + 1);
for(int i = 0; i < 3; i++)
printf("%d ", a[i]);
printf("n");
}
void swap(int *a, int *b) {
int aux = *a;
*a = *b;
*b = aux;
}