In C++, an array is a collection of elements of the same data type stored in contiguous memory locations. Each element in an array can be accessed using an index.
Storing Values in Arrays:
1. Declaration and Initialization:
- Declaration: Define an array by specifying the data type and the number of elements it will hold.
```cpp
int numbers[5]; // Declares an array named 'numbers' that can hold 5 integers
- Initialization: Assign values to the array elements individually or during declaration.
```cpp
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes 'numbers' with specific values
2. Accessing Array Elements:
- Accessing Elements: Elements in an array are accessed using indices (starting from 0).
```cpp
int value = numbers[2]; // Accesses the third element (index 2) of 'numbers'
3. Modifying Array Elements:
- Modifying Elements: Array elements can be changed by assigning new values.
```cpp
numbers[1] = 10; // Changes the value of the second element (index 1) to 10
Example in C++ Code:
Here's an example illustrating the usage of arrays:
```cpp
#include <iostream>
using namespace std;
int main() {
// Declaration and Initialization of an array
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and displaying elements of the array
cout << "Array elements:" << endl;
for (int i = 0; i < 5; ++i) {
cout << "numbers[" << i << "] = " << numbers[i] << endl;
}
// Modifying an element in the array
numbers[1] = 10; // Changes the value of the second element (index 1) to 10
// Displaying the modified array
cout << "\nModified array elements:" << endl;
for (int i = 0; i < 5; ++i) {
cout << "numbers[" << i << "] = " << numbers[i] << endl;
}
return 0;
}
Explanation of Code:
- `int numbers[5] = {1, 2, 3, 4, 5};`
- Declares an array named `numbers` that can hold 5 integers and initializes it with values 1 through 5.
- Accessing and Displaying Elements:
- A loop iterates through the elements of the array and displays their values along with their indices.
- Modifying an Element:
- Changes the value of the second element (index 1) of the array to 10.
- Displaying the Modified Array:
- Another loop displays the modified array elements to show the change made to the array.
This example demonstrates basic array handling in C++, including declaration, initialization, accessing elements using indices, modifying array elements, and displaying their values. Adjust the array size, values, or operations as needed for different scenarios.
0 Comments