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.

You may notice the & symbol in the loop declaration — const std::string& name. In this context, & does not mean "address of" as you may have seen before. Here it declares name as a reference (an alias) directly to each element in the vector, rather than making a copy of it. Think of it as giving a new name to the same piece of data — similar to using a pointer to the element, 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. The alias itself still advances to each new element with every iteration — it is the content you are accessing through the alias that is kept constant, not the loop's progression.

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.

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