Array Basics in C++
What are Arrays?
Arrays are fundamental data structures in C++ that store multiple elements of the same type in contiguous memory locations. They provide a way to organize and manage collections of data efficiently.
Declaring Arrays
In C++, you can declare arrays using the following syntax:
dataType arrayName[arraySize];
Example of Array Declaration
int numbers[5]; // Declares an integer array of size 5
double temperatures[10]; // Declares a double array of size 10
char letters[26]; // Declares a character array of size 26
Initializing Arrays
Arrays can be initialized in several ways:
Method 1: Direct Initialization
int scores[5] = {85, 90, 78, 92, 88};
Method 2: Partial Initialization
int ages[5] = {25, 30}; // Remaining elements are set to 0
Method 3: Automatic Size Determination
int fibonacci[] = {0, 1, 1, 2, 3, 5, 8, 13}; // Size automatically determined
Array Indexing
Arrays use zero-based indexing, meaning the first element is at index 0:
int fruits[3] = {10, 20, 30};
int firstFruit = fruits[0]; // Accessing first element
int secondFruit = fruits[1]; // Accessing second element
Memory Representation
graph LR
A[Array Memory Layout] --> B[Contiguous Memory Blocks]
B --> C[Index 0]
B --> D[Index 1]
B --> E[Index 2]
B --> F[Index n-1]
Key Characteristics
Characteristic |
Description |
Fixed Size |
Size is determined at compile-time |
Same Data Type |
All elements must be of identical type |
Contiguous Memory |
Elements stored in adjacent memory locations |
Zero-Based Indexing |
First element at index 0 |
Common Pitfalls
- No automatic bounds checking
- Fixed size cannot be changed dynamically
- Potential for buffer overflow
Best Practices
- Always initialize arrays before use
- Check array bounds to prevent memory errors
- Consider using
std::array
or std::vector
for more safety
Example Program
#include <iostream>
int main() {
int studentScores[5];
// Input scores
for (int i = 0; i < 5; ++i) {
std::cout << "Enter score for student " << i + 1 << ": ";
std::cin >> studentScores[i];
}
// Calculate average
double total = 0;
for (int score : studentScores) {
total += score;
}
double average = total / 5;
std::cout << "Average score: " << average << std::endl;
return 0;
}
This section provides a comprehensive overview of array basics in C++, suitable for learners on platforms like LabEx who are beginning their programming journey.