Which C++ feature can be used to conveniently iterate over all elements of an array without explicitly using an array index?

Options

  • A. Range-based for loop
  • B. Preprocessor directive
  • C. Namespace declaration
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

A. Range-based for loop

Detailed Explanation

Answer: (A) Range-based for loop

A range-based for loop can be used to iterate over the elements of an array without manually managing the index.

Example:

int a[] = {10, 20, 30};
for(int x : a)
{
cout << x;
}

Here, the loop automatically visits each element of the array.

This feature was introduced in C++11 and makes array traversal simpler and less error-prone.