🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #55

The foreach Loop


The foreach Loop

There is also a "for-each loop" (also known as ranged-based for loop), which is used to loop through elements in an array (or other data structures):

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 num : myNumbers) {

cout << num << "\n";
}

Loop Through a String

You can also use a for-each loop to loop through characters in a string:

Example

string word = "Hello";
for (char c : word) {
  cout << c << "\n";
}

Note: Don't worry if you don't understand the examples above. You will learn more about arrays in the C++ Arrays chapter. Good to know: The for-each loop was introduced in C++ version 11 (2011).

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

The foreach Loop – FAQs

Quick answers about learning The foreach Loop in C++.

This free note from CodingNow 2.0 explains The foreach Loop in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including The foreach Loop, is 100% free with no signup required.
With focused practice, most students grasp The foreach Loop in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now