Array Operations
Array operations refer to the common tasks performed on arrays, such as insertion, deletion, and updating of elements. These operations are fundamental when working with arrays and are essential for manipulating and organizing data.
Insertion
Insertion involves adding an element at a specific position within an array. To insert an element, you need to shift all the elements to make space for the new element. Here's an example C++ code that demonstrates the insertion of an element at a given index:
1#include <iostream>
2using namespace std;
3
4void insertElement(int arr[], int& size, int index, int value) {
5 // Check if the index is valid
6 if (index < 0 || index > size) {
7 cout << "Invalid index" << endl;
8 return;
9 }
10
11 // Shift elements to make space for the new element
12 for (int i = size; i > index; i--) {
13 arr[i] = arr[i - 1];
14 }
15
16 // Insert the new element
17 arr[index] = value;
18 size++;
19}
Deletion
Deletion involves removing an element from a specific position within an array. When an element is deleted, all the elements after it are shifted to fill the empty space. Here's an example C++ code that demonstrates the deletion of an element at a given index:
1#include <iostream>
2using namespace std;
3
4void deleteElement(int arr[], int& size, int index) {
5 // Check if the index is valid
6 if (index < 0 || index >= size) {
7 cout << "Invalid index" << endl;
8 return;
9 }
10
11 // Shift elements to fill the empty space
12 for (int i = index; i < size - 1; i++) {
13 arr[i] = arr[i + 1];
14 }
15
16 size--;
17}
Updating
Updating involves modifying the value of an element at a specific index within an array. You can update the element by directly assigning a new value to it. Here's an example C++ code that demonstrates the updating of an element at a given index:
1#include <iostream>
2using namespace std;
3
4void updateElement(int arr[], int size, int index, int value) {
5 // Check if the index is valid
6 if (index < 0 || index >= size) {
7 cout << "Invalid index" << endl;
8 return;
9 }
10
11 // Update the element
12 arr[index] = value;
13}
These array operations are crucial for manipulating and organizing data efficiently. By mastering these operations, you'll be able to work with arrays more effectively.
xxxxxxxxxx
}
using namespace std;
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void insertElement(int arr[], int& size, int index, int value) {
if (index < 0 || index > size) {
cout << "Invalid index" << endl;
return;
}
for (int i = size; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = value;
size++;
}
void deleteElement(int arr[], int& size, int index) {
if (index < 0 || index >= size) {
cout << "Invalid index" << endl;
return;
}