Swap Two Arrays Without Using Temporary Variable in C



Swap two arrays without using a temporary variable. We will use arithmetic and bitwise Operators instead of a third variable.

The logic to read the first array is as follows ?

printf("enter first array ele:");
for(i = 0; i < size; i++){
   scanf("%d", &first[i]);
}

The logic to read the second array is as follows ?

printf("enter first array ele:");
for(i = 0; i < size; i++){
   scanf("%d", &first[i]);
}

The logic to swap the two arrays without using a third variable is as follows ?

for(i = 0; i < size; i++){
   first[i] = first[i] + sec[i];
   sec[i] = first[i] - sec[i];
   first[i] = first[i] - sec[i];
}

Program

The following C program swaps two arrays without using a temporary variable. It reads the array size and elements, then swaps them using arithmetic operations ?

#include<stdio.h>
int main(){
   int size, i, first[20], sec[20];
   printf("enter the size of array:");
   scanf("%d", &size);
   printf("enter first array ele:");
   for(i = 0; i < size; i++){
      scanf("%d", &first[i]);
   }
   printf("enter second array ele:");
   for(i = 0; i < size; i ++){
      scanf("%d", &sec[i]);
   }
   //Swapping two Arrays
   for(i = 0; i < size; i++){
      first[i] = first[i] + sec[i];
      sec[i] = first[i] - sec[i];
      first[i] = first[i] - sec[i];
   }
   printf("first array after swapping %d elements ", size);
   for(i = 0; i < size; i ++){
      printf(" %d \t ",first[i]);
   }
   printf("sec array after Swapping %d elements", size);
   for(i = 0; i < size; i ++){
      printf(" %d \t ",sec[i]);
    }
   return 0;
}

Output

When the above program is executed, it produces the following result ?

enter the size of array:5
enter first array ele:
11 12 13 14 15
enter second array ele:
90 80 70 60 50
first array after swapping 5 elements
90 80 70 60 50
sec array after Swapping 5 elements
11 12 13 14 15
Updated on: 2024-12-09T16:53:46+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements