C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Swap two arrays using pointers

C Program: Swap two arrays using pointers

C

#include <stdio.h>

 

#define SIZE 5

 

// Function to swap two arrays using pointers

void swapArrays(int *a, int *b, int n) {

    int temp;

    for (int i = 0; i < n; i++) {

        temp = *(a + i);

        *(a + i) = *(b + i);

        *(b + i) = temp;

    }

}

 

int main() {

    int arr1[SIZE], arr2[SIZE];

 

    printf("Enter %d elements for first array:\n", SIZE);

    for (int i = 0; i < SIZE; i++)

        scanf("%d", &arr1[i]);

 

    printf("Enter %d elements for second array:\n", SIZE);

    for (int i = 0; i < SIZE; i++)

        scanf("%d", &arr2[i]);

 

    printf("\nBefore swapping:\n");

    printf("Array 1: ");

    for (int i = 0; i < SIZE; i++)

        printf("%d ", arr1[i]);

 

    printf("\nArray 2: ");

    for (int i = 0; i < SIZE; i++)

        printf("%d ", arr2[i]);

 

    // Swap arrays using pointers

    swapArrays(arr1, arr2, SIZE);

 

    printf("\n\nAfter swapping:\n");

    printf("Array 1: ");

    for (int i = 0; i < SIZE; i++)

        printf("%d ", arr1[i]);

 

    printf("\nArray 2: ");

    for (int i = 0; i < SIZE; i++)

        printf("%d ", arr2[i]);

 

    printf("\n");

 

    return 0;

}

Output

 
OUTPUT :
Enter 5 elements for first array:
1 2 3 4 5
Enter 5 elements for second array:
6 7 8 9 10

Before swapping:
Array 1: 1 2 3 4 5
Array 2: 6 7 8 9 10

After swapping:
Array 1: 6 7 8 9 10
Array 2: 1 2 3 4 5

Explanation

Concept

Description

swapArrays(int *a, int *b, int n)

Function takes pointers to two integer arrays.

*(a + i) and *(b + i)

Access array elements using pointer arithmetic.

Loop

Swaps elements one by one.

No third array

Only one temp variable is used to exchange values.