C++ Program to Copy All the Elements of One Array to Another in the Reverse Order

15/05/2024 0 By indiafreenotes

Copying all the elements of one array to another in reverse order in C++ can be achieved by iterating through the source array from the last element to the first element and copying each element to the destination array from the first element to the last. Here’s an example program that demonstrates how to do this:

#include <iostream>

void reverseCopyArray(const int source[], int destination[], int size) {

    // Iterate through the source array from the last element to the first

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

        // Copy the element from source[i] to destination[size – 1 – i]

        destination[i] = source[size – 1 – i];

    }

}

int main() {

    // Define the source array

    int source[] = {10, 20, 30, 40, 50};

    int size = sizeof(source) / sizeof(source[0]);

    // Define the destination array

    int destination[size];

    // Copy all the elements of the source array to the destination array in reverse order

    reverseCopyArray(source, destination, size);

    // Output the destination array

    std::cout << “Destination array with elements in reverse order: “;

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

        std::cout << destination[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The function reverseCopyArray takes a source array, a destination array, and the size of the arrays as parameters.
  • The function iterates through the source array from the first element (i = 0) to the last element (i = size – 1).
  • In each iteration, it copies the element from source[size – 1 – i] to destination[i], effectively reversing the order of the elements.
  • In the main function, the program outputs the destination array, which contains the elements of the source array in reverse order.