Array manipulation: indexing, iterating, sorting, searching in C++

In C++, arrays can be manipulated in various ways, such as indexing, iterating, sorting, and searching. Here’s an overview of how to perform these operations on arrays in C++:

1. Indexing: Array elements can be accessed using their index, which starts at 0 for the first element. For example:

int arr[5] = {1, 2, 3, 4, 5};

cout << arr[0] << endl; // output: 1
cout << arr[2] << endl; // output: 3

In this example, the first and third elements of the array are accessed using their indices.

2. Iterating: Arrays can be iterated using loops, such as for loops or while loops. For example:

int arr[5] = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

// output: 1 2 3 4 5

In this example, a for loop is used to iterate over the elements of the array and output each element.

3. Sorting: Arrays can be sorted using various algorithms, such as the bubble sort, insertion sort, or quicksort algorithm. Here's an example of how to sort an array using the built-in `sort()` function in C++:

intarr[5] = {5, 2, 4, 1, 3};

sort(arr, arr + 5); // sort the array

for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

// output: 1 2 3 4 5

In this example, the `sort()` function is used to sort the array in ascending order. The function takes two parameters, the beginning and the end of the range to be sorted. In this case, the range is the whole array, so the beginning and end are the addresses of the first and last elements of the array.

4. Searching: Arrays can be searched for a specific value using algorithms such as linear search or binary search. Here's an example of how to perform a linear search on an array:

int arr[5] = {1, 2, 3, 4, 5};
int x = 3;
int index = -1;

for (int i = 0; i < 5; i++) {
    if (arr[i] == x) {
        index = i;
        break;
    }
}

if (index == -1) {
    cout << "Element not found" << endl;
} else {
    cout << "Element found at index " << index << endl;
}

// output: Element found at index 2

Inthis example, a linear search is performed on the array to find the index of the element `x = 3`. The search is performed by iterating over the elements of the array and comparing each element to `x`. If the element is found, the index is stored in the `index` variable and the loop is terminated using the `break` statement. If the element is not found, the value of `index` remains unchanged, and a message is outputted indicating that the element was not found.

By performing these operations on arrays in C++, you can manipulate and analyze collections of elements in a wide range of applications.