Jump to content

C++ Lessons : 18.1. Loop Through an Array


quix
 Share

Recommended Posts

  • Manager

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

Example

string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
  cout << cars << "\n";
}

 

This example outputs the index of each element together with its value:

Example

string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
  cout << i << " = " << cars << "\n";
}

 

And this example shows how to loop through an array of integers:

Example

int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
  cout << myNumbers << "\n";
}

 


The foreach Loop

There is also a "for-each loop" (introduced in C++ version 11 (2011), which is used exclusively to loop through elements in an array:

Syntax

for (type variableName arrayName) {
  // code block to be executed
}

 

The following example outputs all elements in an array, using a "for-each loop":

Example

int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
  cout << i << "\n";
}

 

1.png.56210348f845fad9f2d8f843d77e3c16.png

Click! : adelinrzo

Click! quiixx.

Click! : raizo

 

Guardian of Leaks!

 

image.png.3ca1bf60c26a3523b93df92ea8521802.png (24.01.2023)

image.png.990bdf55e8ebaad7e92cc11967598b8d.png (12.03.2023)

image.png.25e5d76f6f7de46f49423812d3d500a3.png (30.03.2023)

Link to comment
Share on other sites

  • quix locked this topic
Guest
This topic is now closed to further replies.
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...