Programing: How to swap the elements of 2 arrays without using a temp variable

I don’t know what to say here lets get into it
Usually you would assign the first element of array1 to a temp variable and then assign the first element of array2 to the first element of array1 and then assign the value of temp to the first element of array2, and keep doing this for the rest of the elements of both arrays.
But what if we don’t want to use a temp variable?

this is how you do it :

int main()
{
int Array1[]={12,4,8,6,10};
int Array2[]={1,3,4,7,9};
int i;
printf(“Array1 t Array2 n”);
for(i=0;i<5;i++){
//Printing the arrays before swapping
printf(“%d t %d n”,Array1[i],Array2[i]);
}
printf(“n————— n”);
for(i=0;i<5;i++){
//Swapping the elements
Array1[i]=Array1[i]+Array2[i];
Array2[i]=Array1[i]-Array2[i];
Array1[i]=Array1[i]-Array2[i];

//Printing the elements after swapping
printf(“%d t %d n”,Array1[i],Array2[i]);
}
    return 0;
}

And the output is:

Array1   Array2
12       1
4        3
8        4
6        7
10       9

—————
1        12
3        4
4        8
7        6
9        10

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

Hope i helped and drop your questions in the comments below if you have any.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments