C Program to Swap Two Arrays Without Using Temp Variable

In this tutorial, i am going to show you how to swap two arrays without using temp variable in the c program.

All C Programs to Swap Two Arrays Without Using Temp Variable

  • C Program to Swap Two Arrays Without Using Temp Variable Using For Loop
  • C Program to Swap Two Arrays Without Using Temp Variable Using Bitwise Operator

C Program to Swap Two Arrays Without Using Temp Variable Using For Loop

/* C Program to Swap Two Arrays Without Using Temp Variable */
#include<stdio.h>
int main()
{
 int Size, i, a[10], b[10], Temp[10];
  
 printf("\nPlease Enter the Size of the Array\n");
 scanf("%d", &Size);
 
 printf("\nPlease Enter the First Array Elements\n");
 for(i = 0; i < Size; i++)
  {
      scanf("%d", &a[i]);
  }
   
 printf("\nPlease Enter the Second Array Elements\n");
 for(i = 0; i < Size; i ++)
  {
      scanf("%d", &b[i]);
  }
 //Swapping two Arrays 
 for(i = 0; i < Size; i++)
  {
    a[i] = a[i] + b[i];
    b[i] = a[i] - b[i]; 
    a[i] = a[i] - b[i];
  }
 printf("\n a[%d] Array Elements After Swapping \n", Size); 
 for(i = 0; i < Size; i ++)
  {
      printf(" %d \t ",a[i]);
  }
printf("\n\n b[%d] Array Elements After Swapping \n", Size); 
 for(i = 0; i < Size; i ++)
  {
      printf(" %d \t ",b[i]);
  }
  return 0;
} 

The result of the above c program; as follows:

Please Enter the Size of the Array
5
Please Enter the First Array Elements
1 2 3 4 5
Please Enter the Second Array Elements
6 7 8 9 10
a[5] Array Elements After Swapping 
 6 	  7 	  8 	  9 	  10 	 

 b[5] Array Elements After Swapping 
 1 	  2 	  3 	  4 	  5 

C Program to Swap Two Arrays Without Using Temp Variable Using Bitwise Operator

/* C Program to Swap Two Arrays Without Using Temp Variable */
#include<stdio.h>
int main()
{
 int Size, i, a[10], b[10], Temp[10];
  
 printf("\nPlease Enter the Size of the Array\n");
 scanf("%d", &Size);
 
 printf("\nPlease Enter the First Array Elements\n");
 for(i = 0; i < Size; i++)
  {
      scanf("%d", &a[i]);
  }
   
 printf("\nPlease Enter the Second Array Elements\n");
 for(i = 0; i < Size; i ++)
  {
      scanf("%d", &b[i]);
  }
 //Swapping two Arrays 
 for(i = 0; i < Size; i++)
  {
    a[i] = a[i] ^ b[i];
    b[i] = a[i] ^ b[i]; 
    a[i] = a[i] ^ b[i];
  }
 printf("\n a[%d] Array Elements After Swapping \n", Size); 
 for(i = 0; i < Size; i ++)
  {
      printf(" %d \t ",a[i]);
  }
printf("\n\n b[%d] Array Elements After Swapping \n", Size); 
 for(i = 0; i < Size; i ++)
  {
      printf(" %d \t ",b[i]);
  }
  return 0;
} 

The result of the above c program; as follows:

Please Enter the Size of the Array
5
Please Enter the First Array Elements
1 2 3 5 6
Please Enter the Second Array Elements
10 20 30 40 50
a[5] Array Elements After Swapping 
 10 	  20 	  30 	  40 	  50 	 

 b[5] Array Elements After Swapping 
 1 	  2 	  3 	  5 	  6 	

More C Programming Tutorials

Leave a Comment