Considering A as a one-dimensional array, which of the following C++…
2018
Considering A as a one-dimensional array, which of the following C++ statements will print the third element of A?
- A.
cout << A[3];
- B.
cout << 3[A];
- C.
cout << 2[A];
- D.
cout >> A[2];
Attempted by 139 students.
Show answer & explanation
Correct answer: C
Concept
In C and C++, array indexing is zero-based: the element at position k (counting from 1) lives at index k - 1. The subscript operator is also commutative, because a[i] is defined as *(a + i); since addition commutes, a[i] equals i[a] for any array a and integer i.
Applying it here
The third element is at index 3 - 1 = 2, i.e.
A[2].By commutativity of the subscript,
A[2]is the same as2[A], both expanding to*(A + 2).To send a value to standard output you use the insertion operator
<<, socout << 2[A];prints that element.
Cross-check
Expanding 2[A] as *(A + 2) confirms it dereferences the same address as A[2], and << (not >>) is the output operator, so the statement both targets the right element and actually prints it.