Topic 21 of 83
Arrays
Overview
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows you to group related variables together under a single name.
Syntax
cpp
// Declaration and Initialization
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing elements (0-indexed)
int first = numbers[0]; // 10
// Modifying elements
numbers[4] = 99; // Changes 50 to 99Common Pitfalls
- Accessing out of bounds (e.g., `numbers[5]`). C++ does not check array bounds, leading to silent undefined behavior or memory corruption.
Interview Tips
- Explain that arrays in C++ do NOT store their own size. You have to pass the size manually to functions, or use `sizeof(arr)/sizeof(arr[0])`.
- In modern C++, `std::vector` or `std::array` is heavily preferred over raw C-style arrays due to safety and utility.
Real-World Example
Calculating the average score of a class.
example
cpp
#include <iostream>
using namespace std;
int main() {
int scores[] = {85, 92, 78, 90, 88}; // Size inferred as 5
int n = sizeof(scores) / sizeof(scores[0]);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += scores[i];
}
cout << "Average: " << (float)sum / n << "\n";
return 0;
}