Menu
Coddy logo textTech

Enhanced For Loop

Part of the Fundamentals section of Coddy's C++ journey — lesson 65 of 74.

The enhanced for loop, also known as the for-each loop, provides a simpler way to iterate through arrays. It automatically handles the indexing and retrieval of elements, making the code more readable and less prone to errors.

Here's the basic syntax of an enhanced for loop:

for (data_type element : array) {
    // Code to be executed for each element
}
  • data_type: The type of elements in the array.
  • element: A variable that will hold the current element in each iteration.
  • array: The array you want to iterate over.

Here's an example:

int numbers[] = {1, 2, 3, 4, 5};
for (int number : numbers) {
    std::cout << number << std::endl;
}

In this example, the loop iterates over the numbers array. In each iteration, the current element is assigned to the number variable, and the code inside the loop is executed. The output will be:

1
2
3
4
5

The enhanced for loop is especially useful when you need to access each element in an array without modifying the array itself.

challenge icon

Challenge

Easy

Create a program that does the following:

  1. Initializes an array of strings named fruits with the values "apple", "banana", "orange", "grape", and "kiwi".
  2. Uses an enhanced for loop to iterate over the fruits array.
  3. In each iteration, prints the current fruit

Cheat sheet

The enhanced for loop (for-each loop) provides a simpler way to iterate through arrays without manual indexing:

for (data_type element : array) {
    // Code to be executed for each element
}

Example with integer array:

int numbers[] = {1, 2, 3, 4, 5};
for (int number : numbers) {
    std::cout << number << std::endl;
}

The enhanced for loop is useful when you need to access each element without modifying the array.

Try it yourself

#include <iostream>
#include <string>


int main() {
    // Initialize the fruits array
    std::string fruits[] = {"apple", "banana", "orange", "grape", "kiwi"};

    // Use an enhanced for loop to iterate over the array
    
    return 0;
}
quiz iconTest yourself

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

All lessons in Fundamentals