Arrays
C++ Arrays
Definition: An array is a collection of multiple values of the same data type stored in contiguous memory locations. Instead of declaring separate variables for related data (like mark1, mark2, etc.), you can store them all under a single variable name and access them using an index.
Why: Standard beginner resources include arrays as a core topic immediately after loops. Arrays provide the first introduction to data structures; they allow you to handle large amounts of information efficiently, which is the foundation for advanced concepts like sorting, searching, and managing databases.
Declaration and Initialization Syntax
To create an array, you must specify the Data Type, the Array Name, and the Size (the number of elements it will hold) inside square brackets.
dataType arrayName[size] = {value1, value2, value3};
Example: Storing and Printing Marks
The most efficient way to work with an array is by using a for loop. In this example, we iterate through an array of 5 integers and print each value to the console:
#include <iostream> using namespace std; int main() { // Declaring and initializing an array of 5 integers int marks[5] = {78, 85, 90, 67, 88}; // Using a for loop to access array elements by index for (int i = 0; i < 5; i++) { cout << "Mark at index " << i << ": " << marks[i] << endl; } return 0; }
Essential Characteristics of Arrays
| Feature | Description |
|---|---|
| Zero-Based Indexing | The first element is always at index 0. The last element is at index size - 1. |
| Fixed Size | Once declared, the size of a standard array cannot be changed during program execution. |
| Same Data Type | All elements in an array must be of the same type (e.g., all int or all char). |
| Random Access | You can access any element directly if you know its index (e.g., marks[3]), which is very fast. |
Key Notes
- Array Boundaries: C++ does not check if an index is valid. If you try to access
marks[10]in an array of size 5, the program will access a random memory location, leading to "undefined behavior" or crashes. This is known as an Out of Bounds error. - Partial Initialization: If you provide fewer values than the specified size (e.g.,
int arr[5] = {10, 20};), the remaining elements are automatically initialized to0. - Omitting Size: You can omit the size if you initialize it immediately:
int arr[] = {1, 2, 3};. The compiler will automatically count the elements and set the size to 3. - Modern Alternatives: While basic arrays are fundamental, modern C++ often uses
std::vectorfrom the Standard Template Library (STL) because vectors can grow in size dynamically and are generally safer to use.