by Dinesh Thakur Category: Array

Any operation on an array has to be carried out element by element. It cannot be performed on the array as a whole. Therefore, in swapping also, an element of one array is swapped with an element of another array. The two may not have the same index value if you are not dealing with vectors and matrices.

In Program, we define a function Swap which carries out the process. For changing the values of variables, it has to be passed on to the function by pointers and not by values. This is because when the variable is passed on by value, only copy of the variable value is passed on to the function. The function may change the value of the copy but the original value of the variable remains unchanged. Program provides an illustration of this concept. In such cases, the function is called with addresses of variables as the arguments.

Illustrates swapping of elements of two arrays

#include <stdio.h>

void Swap (int *x, int *y) // definition of Swap with pointers
{
  int Temp;
  Temp = *y ;
  *y = *x;
  *x =Temp;
} // end of function
void main()
{
  int i, j;
  int Dal [4] = {4, 5, 6, 7};
  int San[4] = {21, 22, 23, 24};
  clrscr();
  for ( i =0; i<4;i++)
    {
         Swap (&Dal[i] , &San[i]);
    /*addresses of variables are passed on to the function Swap()*/
         printf("Dal[%d] =%d, ",i, Dal[i] );
    }
         printf ("\n");
         for (j =0; j<4; j++)
           printf("San[%d] = %d, ",j, San[j]);
}

C Program swapping of elements of two arrays



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles