Arrays in C++ - Notes
Arrays in C++
-----------------
1. Definition:
- An array is a collection of variables of the same type stored in contiguous memory locations.
- Syntax: `data_type array_name[array_size];`
2. Example:
```cpp
int numbers[5] = {1, 2, 3, 4, 5};
```
3. Accessing Array Elements:
- Array elements are accessed using the index, starting from 0.
- Example: `numbers[0]` gives 1, `numbers[1]` gives 2, etc.
4. Iterating through an Array:
- Using loops, we can traverse an array:
```cpp
for(int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
```
5. Multi-Dimensional Arrays:
- Arrays can have more than one dimension.
- Example:
```cpp
int matrix[2][2] = {{1, 2}, {3, 4}};
```
6. Common Operations:
- Accessing: `array[index]`
- Modifying: `array[index] = value`
- Finding size: `sizeof(array)/sizeof(array[0])`
- Example:
```cpp
int size = sizeof(numbers)/sizeof(numbers[0]);
```
7. Passing Arrays to Functions:
- Arrays can be passed to functions by reference.
- Example:
```cpp
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
```
8. Important Points:
- Arrays have fixed size.
- Arrays are stored in contiguous memory locations.
- The name of the array is a pointer to the first element of the array.