Using Arrays with Loops in C++

Loops are commonly used to access and manipulate array elements efficiently. The for loop is particularly useful for iterating over arrays.

Example: Printing Array Elements

#include <iostream>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int arraySize = sizeof(numbers) / sizeof(numbers[0]);
    
    for (int i = 0; i < arraySize; i++) {
        std::cout << "Element " << i << ": " << numbers[i] << std::endl;
    }
    return 0;
}

Key Takeaways

  • Loops allow for efficient traversal of arrays.
  • Use sizeof() to determine array size when necessary.
  • Ensure the loop index stays within array bounds to prevent errors.