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
5The enhanced for loop is especially useful when you need to access each element in an array without modifying the array itself.
Challenge
EasyCreate a program that does the following:
- Initializes an array of strings named
fruitswith the values"apple","banana","orange","grape", and"kiwi". - Uses an enhanced
forloop to iterate over thefruitsarray. - 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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else