Loading...
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Introduced in C++11, these loops provide a cleaner, more readable way to iterate over all elements in a container or array.
vector<int> nums = {10, 20, 30};
for (int n : nums) {
cout << n << " ";
}Reads as: "For each integer n in nums".
for (const auto &n : nums) {
cout << n << " ";
}Using & avoids copying each element, and const prevents accidental modification.
Use whenever you need to visit EVERY element and don't need the index. If you need the index (e.g., i), use a traditional for loop.