🔁
Basics

Loops in C++

for, while, range-based for
💡 for aur while loops C jaise hi hain — lekin C++11 ne ek naya, bahut simpler loop diya: "range-based for", jo kisi bhi collection (array, vector) ke har element par seedha ghoomta hai, bina index manage kiye.

for, while, do-while syntax C se same hai. Range-based for (C++11+) collections traverse karne ka sabse clean tarika hai — index ki zaroorat nahi, out-of-bounds errors ka risk khatam.

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

// Traditional (C jaisa):
for (int i = 0; i < 5; i++) {
  cout << arr[i] << " ";
}

// Range-based for (C++11+, simpler):
for (int val : arr) {
  cout << val << " ";
}
cout << endl;
🔁
for aur while loops C jaise hi hain — lekin C++11 ne ek naya, bahut simpler loop diya: "range-based for", jo kisi bhi collection (array, vector) ke har element par seedha ghoomta hai, bina index manage kiye.
1 / 2
⚡ Quick Recap
  • for/while/do-while C jaise hi hain
  • Range-based for (C++11+) = simpler, index-free traversal
  • & (reference) ke saath elements modify bhi kar sakte ho
On this page (1 subtopics)

Loops ko nest karke 2D patterns/grids process kar sakte ho — outer loop rows, inner loop columns. Bahut common hai matrices, tables, ya patterns print karne mein.

for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= 3; j++) {
    cout << i * j << " ";
  }
  cout << endl;
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
💡Tip: Nested loops ka time complexity usually O(n²) hota hai (do loops, har ek n baar) — bade inputs ke liye performance ka khayal rakho.