swap() – swap array elements

The code is a C++ program that uses the array data structure from the <array> library. It declares two array objects firstArray and secondArray with 9 elements each.

The firstArray is initialized with values 1, 2, 3, 4, 5, 6, 7, 8, 9, and secondArray with values 10, 20, 30, 40, 50, 60, 70, 80, 90.

The code then prints the elements of the firstArray and secondArray before swapping them.

Next, the firstArray and secondArray are swapped using the swap() method. This method swaps the contents of the two arrays.

Finally, the code prints the elements of the firstArray and secondArray after swapping them. The elements of firstArray would be 10, 20, 30, 40, 50, 60, 70, 80, 90, and the elements of secondArray would be 1, 2, 3, 4, 5, 6, 7, 8, 9.

#include &lt;iostream&gt;
#include &lt;array&gt;
using namespace std;

int main() {
    array<int, 9> firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    array<int, 9> secondArray = {10, 20, 30, 40, 50, 60, 70, 80, 90};

    cout << "before swapping" << endl;
    cout << "first array" << endl;
    for (int i = 0; i < 9; i++) {
        cout << firstArray.at(i) << " ";
    }

    cout << "\nsecond array" << endl;
    for (int i = 0; i < 9; i++) {
        cout << secondArray.at(i) << " ";
    }

    firstArray.swap(secondArray);

    cout << "\n\nafter swapping" << endl;
    cout << "first array" << endl;
    for (int i = 0; i < 9; i++) {
        cout << firstArray.at(i) << " ";
    }

    cout << "\nsecond array" << endl;
    for (int i = 0; i < 9; i++) {
        cout << secondArray.at(i) << " ";
    }

    return 0;
}
Output
before swapping
first array
1 2 3 4 5 6 7 8 9 
second array
10 20 30 40 50 60 70 80 90 

after swapping
first array
10 20 30 40 50 60 70 80 90 
second array
1 2 3 4 5 6 7 8 9