C++ foreach Loop

πŸ” C++ foreach Loop (Range-Based for Loop)

C++ mein foreach loop ko officially range-based for loop kehte hain.
Ye arrays, strings, vectors, lists, maps jaise collections ke har element par iterate karne ka simple aur clean tareeqa hai.

Introduced in C++11


Β 1. Syntax

for (data_type variable : collection) {
// code
}
  • variable β†’ har iteration mein current element

  • collection β†’ array / string / vector etc.


Β 2. Array Example

int arr[] = {10, 20, 30, 40};

for (int x : arr) {
cout << x << ” “;
}

Output:

10 20 30 40

Β 3. String Example

string name = "C++";

for (char ch : name) {
cout << ch << ” “;
}

Output:

C + +

Β 4. Vector Example

#include <vector>
using namespace std;
vector<int> v = {1, 2, 3};

for (int n : v) {
cout << n << ” “;
}


Β 5. Using auto (Recommended)

vector<int> v = {5, 10, 15};

for (auto x : v) {
cout << x << ” “;
}

βœ” Cleaner code
βœ” Type automatically detected


Β 6. Modify Elements (Use Reference &)

❌ This will NOT change original values:

for (int x : arr) {
x = x * 2;
}

βœ” Correct way:

for (int &x : arr) {
x = x * 2;
}

Β 7. Read-Only Loop (Use const)

for (const int &x : arr) {
cout << x << " ";
}

βœ” Safe
βœ” Faster for large data


Β 8. foreach vs Normal for

Range-based for Normal for
Short & clean More control
No index needed Index available
Less error-prone Flexible

 9. When NOT to Use foreach ❌

  • Jab index ki zarurat ho

  • Jab partial loop (start/end control) chahiye

  • Jab step size custom ho


❌ Common Mistake

for (int x : 10) { } // ❌ invalid

βœ” Correct:

int arr[] = {10};
for (int x : arr) { }

πŸ“Œ Summary

  • Foreach = range-based for loop

  • Best for arrays, strings, STL containers

  • Use auto + const & for best practice

  • Simple, readable & safe looping

You may also like...