Understanding C++ Arrays
C++ Arrays Arrays in C++ serve the purpose of storing multiple values within a single variable, eliminating the need to declare separate variables for each individual value. To...
C++ Arrays
Arrays in C++ serve the purpose of storing multiple values within a single variable, eliminating the need to declare separate variables for each individual value. To declare an array, begin by defining the variable type, followed by the array's name, and then use square brackets to indicate the number of elements the array will hold.
Here is an example of declaring an array that holds four strings. Inserting values can be done using an array literal, which involves placing the values in a comma-separated list inside curly braces.
To illustrate, creating an array of three integers can be done as follows:
int numbers[3] = {1, 2, 3};
Access the Elements of an Array
To access a specific element within an array, refer to its index number, which is placed inside square brackets []. For instance, to access the first element of an array named cars, use the following syntax:
cout << cars[0];
Note: Array indexes commence at 0, meaning [0] is the first element, [1] is the second element, and so forth.
Change an Array Element
Modifying the value of a specific element in an array can be achieved by referring to its index number:
names[2] = "NewName";
This line of code changes the value of the third element in the names array to "NewName".