What is an Array?
An array is a collection of elements, all of the same type, stored in a contiguous block of memory. This means that all elements are stored next to each other in memory, which makes accessing them very fast.
How Do Arrays Work?
Fixed Size: When you create an array, you need to specify its size, which is the number of elements it can hold. This size cannot be changed later.
Indexing: Each element in the array has an index, starting from 0 for the first element.
Accessing Elements: You can access any element in the array using its index. For example, if you have an array `arr` and you want to access the third element, you would use `arr[2]`.
Creating and Using Arrays in C++
Here’s a simple example to create and use an array in C++:
#include <iostream>
using namespace std;
int main() {
// Create an array of 5 integers
int numbers[5];
// Assign values to each element
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Access and print each element
for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << " is " << numbers[i] << endl;
}
return 0;
}
Output:
Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40
Element at index 4 is 50
Advantages of Arrays
Fast Access: Arrays allow fast access to elements using indices, which makes retrieval operations very efficient.
Simple to Use: Arrays are straightforward to declare, initialize, and use, making them ideal for beginners.
Limitations of Arrays
Fixed Size: Once an array is created, its size cannot be changed. This means you need to know in advance how many elements you will need.
Memory Usage: Arrays occupy a contiguous block of memory, which can be inefficient if the array is large or if there are many arrays.