Mark As Completed Discussion

Arrays Operations

Arrays are a versatile data structure that allows us to efficiently perform various operations such as insertion, deletion, and searching.

Insertion

To insert an element at a specific index in an array, we need to shift all the elements after that index to the right and then assign the new value to the desired index. Here's an example in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5    // Insertion
6    int numbers[5] = {1, 2, 3, 4, 5};
7    int index = 2;
8    int newValue = 10;
9    for (int i = 4; i > index; i--) {
10        numbers[i] = numbers[i - 1];
11    }
12    numbers[index] = newValue;
13
14    // Print the array
15    for (int i = 0; i < 5; i++) {
16        cout << numbers[i] << " ";
17    }
18    cout << endl;
19
20    return 0;
21}

In the above example, we have an array numbers with 5 elements. We want to insert the value 10 at index 2. By shifting the elements after index 2 to the right, we create space for the new value and then assign it to the desired index.

Deletion

To delete an element at a specific index in an array, we simply need to shift all the elements after that index to the left. Here's an example in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5    // Deletion
6    int numbers[5] = {1, 2, 3, 4, 5};
7    int index = 3;
8    for (int i = index; i < 4; i++) {
9        numbers[i] = numbers[i + 1];
10    }
11
12    // Print the array
13    for (int i = 0; i < 4; i++) {
14        cout << numbers[i] << " ";
15    }
16    cout << endl;
17
18    return 0;
19}

In the above example, we have an array numbers with 5 elements. We want to delete the element at index 3. By shifting the elements after index 3 to the left, we effectively remove the element from the array.

Searching

To search for a specific value in an array, we can iterate through the elements and compare each one with the search value. If we find a match, we can return the index. Here's an example in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5    // Searching
6    int numbers[5] = {1, 2, 3, 4, 5};
7    int searchValue = 4;
8    int foundIndex = -1;
9    for (int i = 0; i < 5; i++) {
10        if (numbers[i] == searchValue) {
11            foundIndex = i;
12            break;
13        }
14    }
15
16    cout << "The element " << searchValue << " is found at index " << foundIndex << endl;
17
18    return 0;
19}

In the above example, we have an array numbers with 5 elements. We want to search for the value 4. By iterating through the elements and comparing each one with the search value, we can find the index at which the element is present.

Arrays operations like insertion, deletion, and searching are fundamental in many algorithms and applications. Understanding these operations is essential for efficient programming and problem-solving.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment