Swap two arrays using pointers

C program to swap two arrays using pointers

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50

void input_array(int arr[], int n);
void print_array(int arr[], int n);

void main()
{
	int arr1[MAX], arr2[MAX];
    int n, i, temp;
    int *ptr1, *ptr2;

    ptr1 = arr1;      //pointer ptr1 points to arr1[0]
    ptr2 = arr2;      //pointer ptr2 points to arr2[0]

    printf("Enter the size of the array\t:");
    scanf("%d",&n);

    printf("\nEnter elements of the first array\n");
    input_array(arr1, n);

    printf("\nEnter elements of the second array\n");
    input_array(arr2, n);

    printf("\nSource array before swapping: ");
    print_array(arr1, n);

    printf("\nDestination array before swapping: ");
    print_array(arr2, n);

    for(i=0;i<n;i++)
    {
        temp = *ptr1;
        *ptr1 = *ptr2;
        *ptr2 = temp;
        ptr1++;
        ptr2++;
    }

    printf("\n\nSource array after swapping: ");
    print_array(arr1, n);

    printf("\nDestination array after swapping: ");
    print_array(arr2, n);

    getch();
}

void input_array(int *arr, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
}

void print_array(int *arr, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("%d ",arr[i]);
    }
}

Output

Enter the size of the array     :5

Enter elements of the first array
1
2
3
4
5

Enter elements of the second array
6
7
8
9
0

Source array before swapping: 1 2 3 4 5
Destination array before swapping: 6 7 8 9 0

Source array after swapping: 6 7 8 9 0
Destination array after swapping: 1 2 3 4 5

Explanation

In the above program, we have to swap two arrays using pointers. For this purpose, number of elements in the array 'n' and elements of the array 'arr1' and 'arr2' are taken as an input from the user. Two pointers 'ptr1' and 'ptr2' are declared and points to array 'arr1' and array 'arr2' respectively.
ptr1 = arr1;
ptr2 = arr2;

To input the arrays, input_array() function is used. This function takes array 'arr' and number of elements in the array 'n' as arguments

To swap the arrays 'arr1' and 'arr2', following procedure is followed.
swap the elements using the statements
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
Pointers 'ptr1' and 'ptr2' are incremented by 1, so that, they point to the next element of their respective arrays.
ptr1++;
ptr2++;
The above procedure is repeated 'n' number of times

To print the arrays, print_array() function is used. This function takes array 'arr' and number of elements in the array 'n' as arguments