C++ Array traversal and manipulation
The process of gaining access to and handling each element of an array is known as array traversal. The process of altering or changing an array’s element values is known as array manipulation.
Here is an example of how to traverse and manipulate a one-dimensional array in C++:
#include <iostream>
using namespace std;
int main() {
// declare and initialize an array
int arr[5] = {3, 8, 1, 6, 2};
// traverse the array and print its elements
cout << "Array before manipulation: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
// manipulate the array by squaring each element
for (int i = 0; i < 5; i++) {
arr[i] = arr[i] * arr[i];
}
// traverse the array and print its elements after manipulation
cout << "Array after manipulation: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:
Array before manipulation: 3 8 1 6 2
Array after manipulation: 9 64 1 36 4
In this example, we first add 5 members to the one-dimensional array arr. The array is then traversed using a for loop, and its elements are printed using cout. The array is then modified by square-rooting each entry in another for loop. The array is then re-explored, and its modified elements are printed using cout.