C++ Arrays

πŸ“¦ C++ Arrays

An array in C++ is a collection of multiple values of the same data type stored in contiguous memory locations and accessed using an index.


πŸ”Ή 1. Array Declaration

data_type array_name[size];

Example:

int marks[5];

πŸ”Ή 2. Array Initialization

Method 1: Initialize at Declaration

int marks[5] = {10, 20, 30, 40, 50};

Method 2: Size Automatically Determined

int marks[] = {10, 20, 30, 40, 50};

πŸ”Ή 3. Access Array Elements

int marks[] = {10, 20, 30};

cout << marks[0]; // 10
cout << marks[1]; // 20

πŸ‘‰ Index starts from 0.


πŸ”Ή 4. Modify Array Elements

marks[1] = 25;

πŸ”Ή 5. Array with for Loop

int arr[] = {5, 10, 15, 20};

for (int i = 0; i < 4; i++) {
cout << arr[i] << ” “;
}


πŸ”Ή 6. Array User Input

int arr[5];

for (int i = 0; i < 5; i++) {
cin >> arr[i];
}


πŸ”Ή 7. Range-Based for Loop (foreach)

int arr[] = {1, 2, 3};

for (int x : arr) {
cout << x << ” “;
}


πŸ”Ή 8. Find Array Length

int arr[] = {10, 20, 30, 40};

int size = sizeof(arr) / sizeof(arr[0]);
cout << size;


πŸ”Ή 9. Multidimensional Array (2D Array)

int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

Access:

cout << matrix[1][2]; // 6

πŸ”Ή 10. Common Array Operations

Sum of Elements

int sum = 0;

for (int x : arr) {
sum += x;
}

Find Maximum

int max = arr[0];

for (int i = 1; i < size; i++) {
if (arr[i] > max)
max = arr[i];
}


❌ Common Mistakes

cout << arr[5]; // ❌ out of bounds

⚠️ Leads to undefined behavior.


πŸ” Array vs Vector

Array Vector
Fixed size Dynamic size
Faster Slightly slower
No bounds checking Safer

πŸ“Œ Summary

  • Arrays store multiple values of the same type

  • Index starts from 0

  • Fixed size

  • Use loops to process elements

You may also like...