Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 2: Control Flow & Modern Functions
CPP ⏱ 10 min read

Loops and Modern Range-based for Loops

Modern C++ eliminates error-prone loop indexing by introducing clean range-based for loops.

What is it?

The range-based for loop (introduced in C++11) executes a loop over a range (like an array, vector, or string) directly without manual index management.

Why is it used?

Eliminates off-by-one errors, is cleaner to read, and works seamlessly across all C++ STL collections.

Detailed Explanation

Range-based for Loop Syntax: • By Value (makes a copy): `for (auto item : container)`. • By Reference (avoids copying, allows modification): `for (auto &item : container)`. • By Const Reference (avoids copying, read-only - Best Practice!): `for (const auto &item : container)`.

Syntax Structure

Syntax Blueprint
for (const auto &item : collection) {
    std::cout << item << "\n";
}

Code Example

CPP Code
#include <iostream>
#include <string>
#include <vector>

int main() {
    // Standard vector container
    std::vector<std::string> courses = {
        "HTML & CSS",
        "JavaScript",
        "Python & Flask",
        "C & C++ Programming",
        "Data Analytics"
    };
    
    std::cout << "=== IGM Curriculum (Range-based Loop) ===\n";
    
    // Read-only range-based loop via const reference
    for (const auto &course : courses) {
        std::cout << "• Course: " << course << "\n";
    }
    
    // Modifying elements in-place using reference &
    std::vector<int> fees = {2500, 2500, 2500};
    for (auto &fee : fees) {
        fee -= 200; // Apply early-bird rebate
    }
    
    std::cout << "\nRebated Fees: ";
    for (const auto &f : fees) {
        std::cout << "₹" << f << " ";
    }
    std::cout << "\n";
    
    return 0;
}

Explanation of the Code

• `const auto &course` accesses elements without allocating extra string copies. • `auto &fee` uses references to mutate elements directly inside the vector.

Expected Output

=== IGM Curriculum (Range-based Loop) === • Course: HTML & CSS • Course: JavaScript • Course: Python & Flask • Course: C & C++ Programming • Course: Data Analytics Rebated Fees: ₹2300 ₹2300 ₹2300

Real-World Application

Used across 99% of modern C++ codebases for traversing vectors, maps, and lists.

Common Mistakes to Avoid

• Iterating large objects by value (`for (auto item : vector)`) which forces expensive copy operations on every iteration. Always use `const auto &`. • Modifying a vector's size (adding/removing items) while iterating over it.

Quick Practice Challenge

Traverse an array of 5 integers and print their squares using a range-based for loop.

Key Takeaways

• Use `for (const auto &item : collection)` for efficient read-only loops. • Use `for (auto &item : collection)` when modifying elements in place. • Eliminates out-of-bounds indexing bugs.