Array Operations
1. Modification:
You can modify the elements of an array by assigning new values to them.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
// Modify the element at index 2
numbers[2] = 10;
// Display the modified array
for (int i = 0; i < 5; ++i) {
std::cout << "Element at index " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
2. Traversal:
You can use loops to traverse through the elements of an array.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
// Using a for loop to traverse the array
for (int i = 0; i < 5; ++i) {
std::cout << "Element at index " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
3. Searching:
You can search for a specific element in an array.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int target = 3;
// Search for the target element
bool found = false;
for (int i = 0; i < 5; ++i) {
if (numbers[i] == target) {
found = true;
break;
}
}
// Display the result
if (found) {
std::cout << "Element " << target << " found in the array." << std::endl;
} else {
std::cout << "Element " << target << " not found in the array." << std::endl;
}
return 0;
}
4. Sorting:
You can sort the elements of an array using algorithms like the bubble sort.
#include <iostream>
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int numbers[5] = {5, 3, 1, 4, 2};
int size = 5;
// Sort the array using bubble sort
bubbleSort(numbers, size);
// Display the sorted array
std::cout << "Sorted array: ";
for (int i = 0; i < size; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
These examples cover some basic array operations, but there are many other operations and algorithms that can be applied to arrays depending on the specific requirements of your program. Understanding these operations is essential for working with arrays effectively in C++.