Complementary task for topic: 6

M Nemeth · 2023-08-29 15:21:04.627218'

Pointers: Swapping Array Elements using Pointers

Pointers: Swapping Array Elements using Pointers

Create a C program that swaps the elements of two arrays using pointers and a separate function. (printarray function and swaparray function)

Hint: Define a function swapArrays that takes two integer pointers as arguments (pointing to the first elements of two arrays) and the size of the arrays.
The function should swap the elements of the two arrays.
In the main function, define two integer arrays arr1 and arr2 of the same size and initialize them with some values.
Print the elements of arr1 and arr2 before calling the swapArrays function.
Call the swapArrays function, passing the addresses of the first elements of arr1 and arr2 along with the size of the arrays.
Print the elements of arr1 and arr2 after calling the swapArrays function to observe the swap.

Solution
#include 

void swapArrays(int* ptr1, int* ptr2, int size) {
    for (int i = 0; i < size; i++) {
        int temp = *(ptr1 + i);
        *(ptr1 + i) = *(ptr2 + i);
        *(ptr2 + i) = temp;
    }
}

void printArray(int* ptr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", *(ptr + i));
    }
    printf("\n");
}

int main() {
    int arr1[] = {1, 2, 3, 4, 5};
    int arr2[] = {6, 7, 8, 9, 10};
    int size = sizeof(arr1) / sizeof(arr1[0]);

    printf("Before Swap:\n");
    printf("arr1: ");
    printArray(arr1, size);
    printf("arr2: ");
    printArray(arr2, size);

    swapArrays(arr1, arr2, size); // Pass the addresses of arr1 and arr2 along with the size

    printf("\nAfter Swap:\n");
    printf("arr1: ");
    printArray(arr1, size);
    printf("arr2: ");
    printArray(arr2, size);

    return 0;
}



Explanation
    In this task, we define a swapArrays function that takes two integer pointers ptr1 and ptr2 as arguments, along with the size of the arrays.

    Inside the swapArrays function, we use a for loop to traverse the arrays using pointer arithmetic.

    For each index, we swap the elements pointed by ptr1 and ptr2 using a temporary variable temp.

    In the main function, we have two integer arrays arr1 and arr2 of the same size with initial values {1, 2, 3, 4, 5} and {6, 7, 8, 9, 10}, respectively.

    We print the elements of arr1 and arr2 before calling the swapArrays function using the printArray function.

    We call the swapArrays function, passing the addresses of the first elements of arr1 and arr2 along with the size.

    After the swap, we print the elements of arr1 and arr2 again using the printArray function to observe that their elements have been swapped.
< < previous    next > >