Menu
Coddy logo textTech

Range-Based For Loop

Part of the Logic & Flow section of Coddy's C++ journey — lesson 15 of 56.

While traditional for loops with indices work well for iterating through vectors, C++ offers a more elegant solution: the range-based for loop. This modern syntax eliminates the need for manual index management and makes your code cleaner and easier to read.

The range-based for loop automatically handles the iteration details for you. Instead of managing an index variable, you simply specify what you want to do with each element:

std::vector<std::string> names = {"Alice", "Bob", "Charlie"};

for (const std::string& name : names) {
    std::cout << name << std::endl;
}

This loop does exactly the same thing as the traditional index-based approach, but with much simpler syntax. The name variable automatically takes on the value of each element in the vector, one at a time.


Notice the & in const std::string& name. Here, & does not mean "address of" as you may have seen before — in a variable declaration like this, it means reference (or alias). Instead of copying each element, name becomes an alias that refers directly to the element in the vector, similar to using a pointer but without needing to dereference it inside the loop body.

The const keyword is a safety measure: it prevents you from accidentally modifying the element through the alias inside the loop body, keeping the original vector data unchanged.

The range-based for loop is not only more readable but also safer - there's no risk of index errors since you're not managing indices manually. It works with any container that supports iteration, making it a versatile tool for processing collections of data in C++.

challenge icon

Challenge

Easy

Create a program that demonstrates the range-based for loop by processing a collection of city names and displaying them with their character counts.

The following inputs will be provided:

  • An integer n representing the number of cities
  • Then n strings representing city names

Your program should:

  1. Create a std::vector<std::string> named cities
  2. Use push_back() to add each of the n city names to the vector
  3. Use a range-based for loop to iterate through the vector
  4. For each city in the loop, print the city name followed by its length using the .length() method
  5. After the loop, print the total number of cities processed using the vector's .size() method

Use the following exact output format:

City: [city name] (Length: [number of characters])\nCity: [city name] (Length: [number of characters])\n...\nTotal cities processed: [total count]

The range-based for loop should use the syntax for (const std::string& city : cities) to iterate through each element in the vector. Use city.length() to get the number of characters in each city name.

Cheat sheet

The range-based for loop iterates through a container without manual index management:

std::vector<std::string> names = {"Alice", "Bob", "Charlie"};

for (const std::string& name : names) {
    std::cout << name << std::endl;
}
  • & declares name as a reference (alias) to each element — no copying
  • const prevents accidental modification of the element inside the loop body
  • Works with any container that supports iteration

Try it yourself

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    // Read the number of cities
    int n;
    cin >> n;
    
    // Create a vector to store city names
    vector<string> cities;
    
    // Read city names and add them to the vector
    for (int i = 0; i < n; i++) {
        string city;
        cin >> city;
        cities.push_back(city);
    }
    
    // TODO: Write your code below
    // Use a range-based for loop to iterate through the cities vector
    // Print each city with its length using the specified format
    // After the loop, print the total number of cities processed
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow