Stage 3: Automatic One-Dimensional Arrays in C++
A guide to static one-dimensional arrays: declaration, initialization, and safe iteration.
One-Dimensional (Automatic) Arrays
An array is a data structure that allows storing multiple elements of the same type in a contiguous memory area. The term "automatic" means memory is reserved on the stack at declaration and freed automatically when the code block ends.
1. Declaration and Initialization
In standard C++, the size of an automatic array must be known at compile time (it must be a constant).
const int SIZE = 5;
int array[SIZE]; // Declaration - contains random values
int numbers[5] = {10, 20, 30, 40, 50}; // Full initialization
int partial[5] = {1, 2}; // The rest (indexes 2, 3, 4) will be zeroed out
int zeroed[100] = {0}; // Quick way to zero out the entire array2. Accessing Elements
Array elements are indexed from 0 to N-1, where N is the number of elements.
int t[3] = {5, 10, 15};
std::cout << t[0]; // Prints 5
t[2] = 100; // Changes 15 to 1003. Iterating through an Array
The most effective way to operate on an array is using a for loop. Remember to use a constant for the size to avoid mistakes.
#include <iostream>
int main() {
const int N = 10;
int data[N];
// Filling the array with user input
for (int i = 0; i < N; i++) {
std::cout << "Enter element " << i << ": ";
std::cin >> data[i];
}
// Displaying the array backwards
for (int i = N - 1; i >= 0; i--) {
std::cout << data[i] << " ";
}
return 0;
}Critical Exam Notes
- No Bounds Checking: C++ does not automatically check if you are going out of bounds. Attempting to write to
array[10]with a size of 10 might overwrite other variables or cause aSegmentation Fault. This is the most common reason for program crashes during exams. - Array Size vs Variable: According to the C++ standard, you should not declare an array with a size provided by a user like this:
int n; cin >> n; int tab[n];(this is a Variable Length Array, which is not part of standard C++). On an exam, it's safer to use a large constant:const int MAX = 1000; int tab[MAX];. - Copying Arrays: You cannot copy an array using a simple assignment
tab1 = tab2;. You must do it element by element within a loop.
Example: Finding the Maximum in an Array
int max = data[0];
for (int i = 1; i < N; i++) {
if (data[i] > max) {
max = data[i];
}
}
std::cout << "Maximum value: " << max;You might also like
Stage 11: Pointer Arithmetic in C++
Understanding how C++ operates on memory addresses. Learn why ptr++ is more than just adding one.
Stage 10: Pointers, Address-of, and Dereference Operators
Understanding the foundations of memory addressing in C++: how pointers and low-level operators work.
Stage 6: C-Style String Handling (char[])
A guide to low-level string processing as null-terminated character arrays, following exam constraints.