How to swap two arrays without using temporary variable in C language?

CServer Side ProgrammingProgramming

Swap two arrays without using Temp variable. Here, we are going to use Arithmetic Operators and Bitwise Operators instead of third variable.

The logic to read the first array is as follows −

printf("enter first array ele:\n");
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:\n");
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

Following is the C program to swap two arrays without using the Temp variable −

 Live Demo

#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:\n");
   for(i = 0; i < size; i++){
      scanf("%d", &first[i]);
   }
   printf("enter second array ele:\n");
   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("\n first array after swapping %d elements\n", size);
   for(i = 0; i < size; i ++){
      printf(" %d \t ",first[i]);
   }
   printf("sec array after Swapping %d elements\n", 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
raja
Published on 24-Mar-2021 17:36:04
Advertisements