You are on page 1of 2

C++ Arrays

C++ Arrays
-Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
-To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should store:
int num[4];
-We have now declared a variable that holds an array of four integers. To insert
values to it, we can use an array literal - place the values in a comma-separated
list, inside curly braces:
int num[4] = {5, 4, 10, 9};
(Access the Elements of an Array)
-You access an array element by referring to the index number.
-This statement accesses the value of the first element in num:
int num[4] = {5, 4, 10, 9};
cout << num[2];
// Outputs 10
-Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
(Change an Array Element)
-To change the value of a specific element, refer to the index number:
int num[4] = {5, 4, 10, 9};
num[2] = 22
cout << num[2];
// Now outputs 22 instead of Volvo 10

C++ Arrays and Loops


Loop Through an Array
-You can loop through the array elements with the for loop.
-The following example outputs all elements in the num array:
int num[4] = {5, 4, 10, 9};
for(int i = 0; i < 4; i++) {
cout << num[i] << "\n";
}
will give an output of:
5
4
10
9
-The following example outputs the index of each element together with its value:
int num[4] = {5, 4, 10, 9};
for(int i = 0; i < 4; i++) {
cout << i << ": " << num[i] << "\n";
}
will give an output of:
0: 5
1: 4
2: 10
3: 9

C++ Omit Array Size


(Omit Array Size)
-You don't have to specify the size of the array. But if you don't, it will only be
as big as the elements that are inserted into it:
int num[] = {5, 4, 10}; // size of array is always 3
-This is completely fine. However, the problem arise if you want extra space for
future elements. Then you have to overwrite the existing values:
int num[] = {5, 4, 10};
into
int num[] = {5, 4, 10, 9, 15};
-If you specify the size however, the array will reserve the extra space:
int num[5] = {5, 4, 10};
-Now you can add a fourth and fifth element without overwriting the others:
num[3] = 9;
num[4] = 15;
(Omit Elements on Declaration)
-It is also possible to declare an array without specifying the elements on
declaration, and add them later:
int num[5];
num[0] = 5;
num[1] = 4;
num[2] = 10;
num[3] = 9;
num[4] = 15;
for(int i = 0; i < 5; i++) {
cout << num[i] <<"\n";
}
will give an output of:
5
4
10
9
15

You might also like