0
0
CppConceptBeginner · 3 min read

What is Range Based For Loop in C++: Simple Explanation and Example

A range-based for loop in C++ is a simple way to loop through all elements in a container like an array or vector without using an index. It automatically accesses each item one by one, making code easier and cleaner.
⚙️

How It Works

Imagine you have a basket full of apples and you want to look at each apple one by one. Instead of counting and picking apples by their position, you just take each apple directly from the basket until none are left. This is how a range-based for loop works in C++.

It goes through every element in a collection like an array or vector automatically. You don’t need to write code to keep track of positions or indexes. The loop gives you each element directly to use inside the loop body.

This makes your code simpler and less error-prone, especially when you only want to read or modify each item in a list.

💻

Example

This example shows how to use a range-based for loop to print all numbers in an array.

cpp
#include <iostream>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    for (int num : numbers) {
        std::cout << num << " ";
    }
    return 0;
}
Output
10 20 30 40 50
🎯

When to Use

Use a range-based for loop when you want to process every item in a container like arrays, vectors, or lists without needing the item's position. It is perfect for reading or modifying elements simply and clearly.

For example, you can use it to sum numbers in a list, print all names in a group, or update values in a collection. It saves time and reduces mistakes compared to traditional loops with indexes.

Key Points

  • Range-based for loops automatically iterate over all elements in a container.
  • They simplify code by removing the need for manual indexing.
  • You can use them with arrays, vectors, and other iterable containers.
  • They improve readability and reduce errors.

Key Takeaways

Range-based for loops let you loop through all elements in a container easily without indexes.
They make your code cleaner and less error-prone by handling element access automatically.
Use them when you want to read or modify every item in arrays, vectors, or similar containers.
They improve code readability and reduce the chance of bugs from manual indexing.