In C++, arrays allow multiple values to be stored within a single variable, making data management more efficient.
Declaring an Array
To define an array, specify the data type, followed by the name and size in square brackets:
string bikeBrands[4];
This declares an array named bikeBrands
that can hold four elements.
To assign values at declaration, use curly braces {}
with a comma-separated list:
string bikeBrands[4] = {"Yamaha", "Ducati", "Kawasaki", "Honda"};
Similarly, an integer array can store numerical values:
int engineSizes[3] = {600, 1000, 1300};
Accessing Elements in an Array
Each array element has an index, starting at 0
. Access elements by using square brackets:
string bikeBrands[4] = {"Yamaha", "Ducati", "Kawasaki", "Honda"}; cout << bikeBrands[0];
Output:
Yamaha
Note: Indexing starts at 0, meaning
[0]
refers to the first element,[1]
to the second, and so on.
Modifying an Array Element
Once an array is initialized, individual elements can be updated by referencing their index.
Example: Changing an Array Value
#include <iostream> using namespace std; int main() { string bikeBrands[4] = {"Yamaha", "Ducati", "Kawasaki", "Honda"}; // Modify the first element bikeBrands[0] = "Harley-Davidson"; cout << bikeBrands[0]; // Now outputs Harley-Davidson instead of Yamaha return 0; }
Output:
Harley-Davidson