Arrays
Arrays
C++ Arrays
• int main() {
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
• cout << cars[0];
• return 0;
• }
• Output:
• Volvo
• Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Change an Array Element
• int main() {
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
• cars[0] = "Opel";
• cout << cars[0];
• return 0;
• }
• Output: opel
C++ Arrays and Loops
• int main() {
• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
• for (int i = 0; i < 5; i++) {
• cout << cars[i] << "\n";
• }
• return 0;
• }
output
• Volvo
BMW
Ford
Mazda
Tesla
This example outputs the index of each
element together with its value:
• #include <iostream>
• #include <string>
• using namespace std;
• int main() {
• string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
• for (int i = 0; i < 5; i++) {
• cout << i << " = " << cars[i] << "\n";
• }
• return 0;
• }
output
• 0 = Volvo
1 = BMW
2 = Ford
3 = Mazda
4 = Tesla
And this example shows how to loop through
an array of integers:
• #include <iostream>
• using namespace std;
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• for (int i = 0; i < 5; i++) {
• cout << myNumbers[i] << "\n";
• }
• return 0;
• }
output
• 10
20
30
40
50
The foreach Loop
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• for (int i : myNumbers) {
• cout << i << "\n";
• }
• return 0;
• }
output
• 10
20
30
40
50
C++ Omit Array Size
• int main() {
• string cars[5];
• cars[0] = "Volvo";
• cars[1] = "BMW";
• cars[2] = "Ford";
• cars[3] = "Mazda";
• cars[4] = "Tesla";
• for(int i = 0; i < 5; i++) {
• cout << cars[i] << "\n";
• }
• return 0;
• }
output
• Volvo
BMW
Ford
Mazda
Tesla
Get the Size of an Array
• To get the size of an array, you can use the sizeof() operator:
• #include <iostream>
• using namespace std;
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• cout << sizeof(myNumbers);
• return 0;
• }
• Output: 20
To get array length
• #include <iostream>
• using namespace std;
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• int getArrayLength = sizeof(myNumbers) / sizeof(int);
• cout << getArrayLength;
• return 0;
• }
• Output 5
Loop Through an Array with sizeof()
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
• cout << myNumbers[i] << "\n";
• }
• return 0;
• }
output
• 10
20
30
40
50
"for-each" loop:
• #include <iostream>
• using namespace std;
• int main() {
• int myNumbers[5] = {10, 20, 30, 40, 50};
• for (int i : myNumbers) {
• cout << i << "\n";
• }
• return 0;
• }
• 10
20
30
40
50
• Next we will study multidimensional arrays