Array Basics
C++ Arrays
In C++, an array is a collection of elements of the same type stored in contiguous memory locations. Each element in the array is accessed by an index or a subscript. Arrays provide a convenient way to store and access a fixed-size sequence of elements.
Declaration and Initialization:
Here's how you declare and initialize an array in C++:
// Declaration
datatype arrayName[size];
// Initialization
datatype arrayName[size] = {value1, value2, ..., valueN};
Example:
#include <iostream>
int main() {
// Declaration of an integer array with size 5
int numbers[5];
// Initialization of an integer array
int values[3] = {10, 20, 30};
// Accessing elements
std::cout << "Element at index 0: " << values[0] << std::endl;
std::cout << "Element at index 1: " << values[1] << std::endl;
std::cout << "Element at index 2: " << values[2] << std::endl;
return 0;
}
Array Indexing:
Array indices start from 0, so the first element of an array is accessed using index 0, the second element with index 1, and so on.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing elements using indices
std::cout << "Element at index 0: " << numbers[0] << std::endl;
std::cout << "Element at index 1: " << numbers[1] << std::endl;
std::cout << "Element at index 2: " << numbers[2] << std::endl;
std::cout << "Element at index 3: " << numbers[3] << std::endl;
std::cout << "Element at index 4: " << numbers[4] << std::endl;
return 0;
}
Array Size:
The size of an array is fixed at the time of declaration, and it cannot be changed during runtime. The size of an array is specified in square brackets during declaration.
#include <iostream>
int main() {
// Array of 3 characters
char name[3] = {'A', 'B', 'C'};
// Array of 4 integers
int ages[4] = {25, 30, 35, 40};
return 0;
}
Iterating Through an Array:
You can use loops, such as for
or while
, to iterate through the elements of an array.
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
// Using a for loop to iterate through the array
for (int i = 0; i < 5; ++i) {
std::cout << "Element at index " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
Arrays are a fundamental concept in C++, and they are extensively used in various applications. Understanding how to declare, initialize, and access elements in an array is crucial for working with C++ programs.